'use client';

import { useState, useCallback, useEffect, useRef } from 'react';
import Link from 'next/link';
import { wordList, countriesWordList } from '@/data/words';
import { useProgress } from '@/hooks/useProgress';
import { useSpeech } from '@/hooks/useSpeech';
import { Word } from '@/types';

type Status = 'idle' | 'correct' | 'incorrect';
type Bank = 'everyday' | 'countries';

function shuffle<T>(arr: T[]): T[] {
  return [...arr].sort(() => Math.random() - 0.5);
}

function scrambleWord(word: string): string {
  let out = word;
  let tries = 0;
  while (out === word && tries < 12) {
    out = shuffle([...word]).join('');
    tries++;
  }
  return out;
}

const difficultyColors: Record<string, string> = {
  easy:   'bg-green-100  text-green-700',
  medium: 'bg-yellow-100 text-yellow-700',
  hard:   'bg-red-100    text-red-700',
};

export default function ScramblePage() {
  const { recordAttempt }   = useProgress();
  const { speak, speaking } = useSpeech();

  const [bank, setBank]       = useState<Bank>('everyday');
  const [words, setWords]     = useState<Word[]>([]);
  const [idx, setIdx]         = useState(0);
  const [scrambled, setScrambled] = useState('');
  const [input, setInput]     = useState('');
  const [status, setStatus]   = useState<Status>('idle');
  const [showHint, setShowHint] = useState(false);
  const [score, setScore]     = useState(0);

  const inputRef = useRef<HTMLInputElement>(null);

  // Re-shuffle word list when bank changes
  useEffect(() => {
    const source = bank === 'everyday' ? wordList : countriesWordList;
    setWords(shuffle(source));
    setIdx(0);
    setInput('');
    setStatus('idle');
    setShowHint(false);
  }, [bank]);

  const current = words[idx];

  useEffect(() => {
    if (current) setScrambled(scrambleWord(current.word));
  }, [current]);

  const handleSubmit = useCallback(() => {
    if (!current || !input.trim()) return;
    const correct = input.trim().toLowerCase() === current.word.toLowerCase();
    setStatus(correct ? 'correct' : 'incorrect');
    recordAttempt(current.id, correct);
    if (correct) setScore(s => s + 1);
  }, [current, input, recordAttempt]);

  const handleNext = useCallback(() => {
    setIdx(i => (i + 1) % words.length);
    setInput('');
    setStatus('idle');
    setShowHint(false);
    setTimeout(() => inputRef.current?.focus(), 80);
  }, [words.length]);

  const handleKey = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') status === 'idle' ? handleSubmit() : handleNext();
  };

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Enter' && status !== 'idle') handleNext();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [status, handleNext]);

  if (!current) return null;

  return (
    <main className="min-h-screen bg-gradient-to-br from-purple-50 via-blue-50 to-indigo-100 p-5">
      <div className="max-w-xl mx-auto">

        {/* Top bar */}
        <div className="flex items-center gap-3 mb-5">
          <Link href="/" className="text-purple-600 hover:text-purple-800 font-bold text-lg">
            ← Back
          </Link>
          <h1 className="text-2xl font-black text-purple-700">Unscramble!</h1>
          <span className="ml-auto text-sm font-bold text-gray-400">
            {idx + 1} / {words.length}
          </span>
        </div>

        {/* ── Word-bank toggle ──────────────────────────────────────────── */}
        <div className="flex bg-white rounded-2xl border-2 border-purple-100 p-1 gap-1 mb-4 shadow-sm">
          <button
            onClick={() => setBank('everyday')}
            className={`flex-1 py-2.5 rounded-xl text-sm font-bold transition-all ${
              bank === 'everyday'
                ? 'bg-purple-600 text-white shadow'
                : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            📚 Everyday Words
          </button>
          <button
            onClick={() => setBank('countries')}
            className={`flex-1 py-2.5 rounded-xl text-sm font-bold transition-all ${
              bank === 'countries'
                ? 'bg-blue-600 text-white shadow'
                : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            🌍 Countries &amp; Nationalities
          </button>
        </div>

        {/* Score */}
        <div className="bg-white rounded-2xl px-4 py-3 mb-4 shadow-sm flex items-center gap-2 border border-purple-100">
          <span className="text-xl">⭐</span>
          <span className="font-bold text-purple-700 text-sm">Score: {score}</span>
        </div>

        {/* Card */}
        <div
          className={`bg-white rounded-3xl shadow-lg p-6 border-2 transition-colors ${
            status === 'correct'   ? 'border-green-400' :
            status === 'incorrect' ? 'border-red-400'   : 'border-purple-100'
          }`}
        >
          {/* Badges */}
          <div className="flex gap-2 mb-4 flex-wrap">
            <span className="bg-purple-100 text-purple-700 text-xs font-bold px-3 py-1 rounded-full">
              {current.category}
            </span>
            <span className={`text-xs font-bold px-3 py-1 rounded-full ${difficultyColors[current.difficulty]}`}>
              {current.difficulty}
            </span>
          </div>

          {/* Definition */}
          <p className="text-gray-700 font-semibold mb-2 leading-relaxed">
            📖 {current.definition}
          </p>
          <p className="text-gray-400 text-sm italic mb-5">
            &ldquo;{current.example}&rdquo;
          </p>

          {/* Scrambled tiles */}
          <div className="bg-purple-50 rounded-2xl p-4 mb-5">
            <p className="text-xs font-black text-purple-400 uppercase tracking-widest text-center mb-3">
              Unscramble these letters
            </p>
            <div className="flex justify-center gap-2 flex-wrap">
              {scrambled.split('').map((letter, i) => (
                <span
                  key={i}
                  className="inline-flex items-center justify-center w-10 h-10 bg-purple-600 text-white font-black text-xl rounded-xl shadow-md select-none"
                >
                  {letter.toUpperCase()}
                </span>
              ))}
            </div>
          </div>

          {/* Hear button */}
          <button
            onClick={() => speak(current.definition)}
            disabled={speaking}
            className="mb-4 px-4 py-2 bg-purple-100 hover:bg-purple-200 text-purple-700 font-bold rounded-xl text-sm transition-all"
          >
            {speaking ? '🔊 Speaking…' : '🔊 Hear the definition'}
          </button>

          {/* Input area */}
          {status === 'idle' && (
            <div>
              <input
                ref={inputRef}
                type="text"
                value={input}
                onChange={e => setInput(e.target.value)}
                onKeyDown={handleKey}
                placeholder="Type the word here…"
                autoComplete="off"
                autoCorrect="off"
                autoCapitalize="off"
                spellCheck={false}
                className="w-full border-2 border-purple-200 rounded-2xl px-4 py-3 text-lg font-bold text-gray-800 focus:outline-none focus:border-purple-500 placeholder-gray-300"
              />

              {showHint ? (
                <p className="text-center text-amber-600 font-bold mt-2 text-sm">
                  💡 {current.word.length} letters, starts with &ldquo;
                  {current.word[0].toUpperCase()}&rdquo;
                </p>
              ) : (
                <button
                  onClick={() => setShowHint(true)}
                  className="w-full text-center text-gray-400 text-sm mt-2 hover:text-purple-500 font-semibold"
                >
                  Need a hint?
                </button>
              )}

              <button
                onClick={handleSubmit}
                disabled={!input.trim()}
                className="w-full mt-4 py-3 rounded-2xl font-black text-lg bg-amber-400 hover:bg-amber-500 text-white shadow-md disabled:opacity-40 disabled:cursor-not-allowed transition-all active:scale-95"
              >
                Check Answer ✓
              </button>
            </div>
          )}

          {/* Result */}
          {status !== 'idle' && (
            <div
              className={`animate-bounce-in text-center p-5 rounded-2xl ${
                status === 'correct' ? 'bg-green-50' : 'bg-red-50'
              }`}
            >
              {status === 'correct' ? (
                <>
                  <p className="text-5xl mb-2">🎉</p>
                  <p className="text-2xl font-black text-green-600">Correct! +1 ⭐</p>
                  <p className="text-green-500 font-bold mt-1">{current.word}</p>
                </>
              ) : (
                <>
                  <p className="text-5xl mb-2">😅</p>
                  <p className="text-xl font-black text-red-600">Almost!</p>
                  <p className="text-gray-600 font-semibold mt-1">
                    The word was:{' '}
                    <span className="text-red-600 font-black">{current.word}</span>
                  </p>
                  <p className="text-gray-400 text-sm mt-1">
                    You typed: &ldquo;{input}&rdquo;
                  </p>
                </>
              )}
              <button
                onClick={handleNext}
                className="mt-4 px-8 py-3 bg-purple-600 hover:bg-purple-700 text-white font-black rounded-2xl shadow-md transition-all active:scale-95"
              >
                Next Word →
              </button>
            </div>
          )}
        </div>
      </div>
    </main>
  );
}
