'use client';

import { useState, useCallback, useRef, useEffect } 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 Difficulty = 'all' | 'easy' | 'medium' | 'hard';
type Status = 'idle' | 'correct' | 'incorrect';
type Bank = 'everyday' | 'countries';

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

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 PracticePage() {
  const { progress, recordAttempt } = useProgress();
  const { speak, speaking } = useSpeech();

  const [bank, setBank]           = useState<Bank>('everyday');
  const [difficulty, setDifficulty] = useState<Difficulty>('all');
  const [words, setWords]         = useState<Word[]>([]);
  const [idx, setIdx]             = useState(0);
  const [input, setInput]         = useState('');
  const [status, setStatus]       = useState<Status>('idle');
  const [showHint, setShowHint]   = useState(false);
  const [sessionCorrect, setSessionCorrect] = useState(0);
  const [sessionTotal, setSessionTotal]     = useState(0);

  const inputRef = useRef<HTMLInputElement>(null);

  // Re-shuffle whenever bank or difficulty changes
  useEffect(() => {
    const source = bank === 'everyday' ? wordList : countriesWordList;
    const filtered =
      difficulty === 'all' ? source : source.filter(w => w.difficulty === difficulty);
    setWords(shuffle(filtered));
    setIdx(0);
    setInput('');
    setStatus('idle');
    setShowHint(false);
  }, [bank, difficulty]);

  const current = words[idx];

  const handleSpeak = useCallback(() => {
    if (current) speak(current.word);
  }, [current, speak]);

  const handleSubmit = useCallback(() => {
    if (!current || !input.trim()) return;
    const correct = input.trim().toLowerCase() === current.word.toLowerCase();
    setStatus(correct ? 'correct' : 'incorrect');
    recordAttempt(current.id, correct);
    setSessionTotal(t => t + 1);
    if (correct) setSessionCorrect(c => c + 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 (
      <div className="min-h-screen flex items-center justify-center bg-purple-50">
        <p className="text-xl font-bold text-gray-400">Loading words…</p>
      </div>
    );
  }

  const isMastered = progress.masteredWords.includes(current.id);

  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">Spell It!</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>

        {/* Session 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">
            {sessionCorrect} / {sessionTotal} correct this session
          </span>
        </div>

        {/* Difficulty filter */}
        <div className="flex gap-2 mb-5 flex-wrap">
          {(['all', 'easy', 'medium', 'hard'] as Difficulty[]).map(d => (
            <button
              key={d}
              onClick={() => setDifficulty(d)}
              className={`px-4 py-2 rounded-full text-sm font-bold transition-all ${
                difficulty === d
                  ? 'bg-purple-600 text-white shadow-md'
                  : 'bg-white text-gray-500 border border-gray-200 hover:border-purple-300'
              }`}
            >
              {d.charAt(0).toUpperCase() + d.slice(1)}
            </button>
          ))}
        </div>

        {/* Word 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 items-center 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>
            {isMastered && (
              <span className="ml-auto bg-yellow-100 text-yellow-700 text-xs font-bold px-3 py-1 rounded-full">
                ⭐ Mastered!
              </span>
            )}
          </div>

          {/* Definition */}
          <p className="text-gray-700 font-semibold mb-2 leading-relaxed">
            📖 {current.definition}
          </p>

          {/* Example */}
          <p className="text-gray-400 text-sm italic mb-5">
            &ldquo;{current.example}&rdquo;
          </p>

          {/* Speak button */}
          <button
            onClick={handleSpeak}
            disabled={speaking}
            className={`w-full py-3 rounded-2xl font-black text-base mb-4 transition-all ${
              speaking
                ? 'bg-purple-200 text-purple-400 cursor-wait'
                : 'bg-purple-600 hover:bg-purple-700 text-white shadow-md hover:shadow-lg active:scale-95'
            }`}
          >
            {speaking ? '🔊 Saying the word…' : '🔊 Hear the Word!'}
          </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">
                  💡 Starts with &ldquo;{current.word[0].toUpperCase()}&rdquo; and has{' '}
                  {current.word.length} letters
                </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 Spelling ✓
              </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">Not quite!</p>
                  <p className="text-gray-600 font-semibold mt-1">
                    The correct spelling is:{' '}
                    <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>
  );
}
