'use client';

import { useState, useCallback, 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 Bank = 'everyday' | 'countries';

// ── helpers ──────────────────────────────────────────────────────────────────

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

function generateWrongSpellings(word: string, allWords: Word[], count = 3): string[] {
  const results = new Set<string>();

  // Use other real words of similar length as distractors
  const pool = shuffle(allWords)
    .map(w => w.word)
    .filter(w => w !== word && Math.abs(w.length - word.length) <= 2);
  for (const w of pool) {
    if (results.size >= count) break;
    results.add(w);
  }

  // Fill remaining with generated misspellings
  const strategies: Array<() => string> = [
    () => {
      const i = Math.floor(Math.random() * (word.length - 1));
      return word.slice(0, i) + word[i + 1] + word[i] + word.slice(i + 2);
    },
    () => {
      const vowels = 'aeiou';
      const indices = [...word].map((c, i) => (vowels.includes(c) ? i : -1)).filter(i => i !== -1);
      if (!indices.length) return word.slice(0, -1);
      const i = indices[Math.floor(Math.random() * indices.length)];
      const other = vowels.replace(word[i], '');
      return word.slice(0, i) + other[Math.floor(Math.random() * other.length)] + word.slice(i + 1);
    },
    () => {
      const indices = [...word].map((c, i) => (!'aeiou'.includes(c) ? i : -1)).filter(i => i !== -1);
      if (!indices.length) return word + 'e';
      const i = indices[Math.floor(Math.random() * indices.length)];
      return word.slice(0, i) + word[i] + word.slice(i);
    },
    () => {
      const i = 1 + Math.floor(Math.random() * (word.length - 1));
      return word.slice(0, i) + word.slice(i + 1);
    },
  ];

  let attempts = 0;
  while (results.size < count && attempts < 30) {
    const candidate = strategies[Math.floor(Math.random() * strategies.length)]();
    if (candidate !== word && candidate.length > 1) results.add(candidate);
    attempts++;
  }
  return Array.from(results).slice(0, count);
}

interface QuizQuestion {
  word: Word;
  options: string[];
  correctIndex: number;
}

function buildQuiz(words: Word[], questionCount = 20): QuizQuestion[] {
  return shuffle(words)
    .slice(0, questionCount)
    .map(word => {
      const wrongs = generateWrongSpellings(word.word, words);
      const options = shuffle([word.word, ...wrongs]);
      return { word, options, correctIndex: options.indexOf(word.word) };
    });
}

// ── component ─────────────────────────────────────────────────────────────────

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

  const [bank, setBank]         = useState<Bank>('everyday');
  const [questions, setQuestions] = useState<QuizQuestion[]>([]);
  const [qIdx, setQIdx]         = useState(0);
  const [selected, setSelected] = useState<number | null>(null);
  const [score, setScore]       = useState(0);
  const [finished, setFinished] = useState(false);

  const startQuiz = useCallback((b: Bank) => {
    const source = b === 'everyday' ? wordList : countriesWordList;
    setQuestions(buildQuiz(source));
    setQIdx(0);
    setSelected(null);
    setScore(0);
    setFinished(false);
  }, []);

  useEffect(() => { startQuiz(bank); }, [bank, startQuiz]);

  const current = questions[qIdx];

  const handleSelect = useCallback(
    (optIdx: number) => {
      if (selected !== null || !current) return;
      setSelected(optIdx);
      const correct = optIdx === current.correctIndex;
      recordAttempt(current.word.id, correct);
      if (correct) setScore(s => s + 1);
    },
    [selected, current, recordAttempt],
  );

  const handleNext = useCallback(() => {
    if (qIdx + 1 >= questions.length) {
      setFinished(true);
    } else {
      setQIdx(i => i + 1);
      setSelected(null);
    }
  }, [qIdx, questions.length]);

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

  // ── results screen ──────────────────────────────────────────────────────
  if (finished) {
    const total = questions.length;
    const pct   = Math.round((score / total) * 100);
    const trophy  = pct >= 80 ? '🏆' : pct >= 60 ? '⭐' : '💪';
    const message = pct >= 80
      ? "Amazing! You're a spelling superstar!"
      : pct >= 60 ? 'Great effort! Keep on practising!'
      : "Don't give up – practice makes perfect!";

    return (
      <main className="min-h-screen bg-gradient-to-br from-purple-50 via-blue-50 to-indigo-100 flex items-center justify-center p-6">
        <div className="max-w-md w-full text-center">
          <div className="bg-white rounded-3xl shadow-xl p-8 border-2 border-purple-200">
            <div className="text-6xl mb-4">{trophy}</div>
            <h2 className="text-3xl font-black text-purple-700 mb-2">Quiz Complete!</h2>
            <p className="text-6xl font-black text-yellow-500 my-4">
              {score}<span className="text-3xl text-gray-400">/{total}</span>
            </p>
            <p className="text-gray-500 font-semibold mb-1">{pct}% correct</p>
            <p className="text-gray-600 font-semibold mb-6">{message}</p>
            <div className="flex gap-3 justify-center">
              <button
                onClick={() => startQuiz(bank)}
                className="px-6 py-3 bg-purple-600 text-white font-black rounded-2xl hover:bg-purple-700 transition-all active:scale-95"
              >
                Try Again
              </button>
              <Link
                href="/"
                className="px-6 py-3 bg-gray-100 text-gray-700 font-black rounded-2xl hover:bg-gray-200 transition-all"
              >
                Home
              </Link>
            </div>
          </div>
        </div>
      </main>
    );
  }

  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 quiz…</p>
      </div>
    );
  }

  // ── quiz screen ──────────────────────────────────────────────────────────
  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">Quiz Time!</h1>
          <span className="ml-auto text-sm font-bold text-gray-400">
            {qIdx + 1} / {questions.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 + progress bar */}
        <div className="bg-white rounded-2xl px-4 py-3 mb-4 shadow-sm flex items-center gap-3 border border-purple-100">
          <span className="font-bold text-purple-700 text-sm shrink-0">⭐ {score} pts</span>
          <div className="flex-1 bg-gray-100 rounded-full h-2.5">
            <div
              className="bg-purple-500 h-2.5 rounded-full transition-all duration-500"
              style={{ width: `${(qIdx / questions.length) * 100}%` }}
            />
          </div>
        </div>

        {/* Question card */}
        <div className="bg-white rounded-3xl shadow-lg p-6 border-2 border-purple-100">
          <p className="text-xs font-black text-purple-400 uppercase tracking-widest mb-3">
            Which one is spelled correctly?
          </p>

          <span className="bg-purple-100 text-purple-700 text-xs font-bold px-3 py-1 rounded-full">
            {current.word.category}
          </span>

          <p className="text-gray-700 font-semibold leading-relaxed mt-3 mb-3">
            📖 {current.word.definition}
          </p>
          <p className="text-gray-400 text-sm italic mb-4">
            &ldquo;{current.word.example}&rdquo;
          </p>

          {/* Hear button */}
          <button
            onClick={() => speak(current.word.word)}
            disabled={speaking}
            className="mb-5 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 word'}
          </button>

          {/* Options grid */}
          <div className="grid grid-cols-2 gap-3">
            {current.options.map((option, i) => {
              let cls = 'border-2 rounded-2xl p-3 font-black text-base transition-all text-left';
              if (selected === null) {
                cls += ' border-gray-200 bg-gray-50 text-gray-700 hover:border-purple-400 hover:bg-purple-50 active:scale-95 cursor-pointer';
              } else if (i === current.correctIndex) {
                cls += ' border-green-400 bg-green-100 text-green-800';
              } else if (i === selected) {
                cls += ' border-red-400 bg-red-100 text-red-800';
              } else {
                cls += ' border-gray-200 bg-gray-50 text-gray-400 opacity-60';
              }
              return (
                <button key={i} onClick={() => handleSelect(i)} disabled={selected !== null} className={cls}>
                  {option}
                </button>
              );
            })}
          </div>

          {/* Feedback */}
          {selected !== null && (
            <div
              className={`mt-4 p-3 rounded-2xl text-center animate-bounce-in ${
                selected === current.correctIndex
                  ? 'bg-green-50 text-green-700'
                  : 'bg-red-50 text-red-700'
              }`}
            >
              {selected === current.correctIndex ? (
                <span className="font-black">🎉 Correct! Well done!</span>
              ) : (
                <span className="font-black">
                  😅 The answer is: <em>{current.word.word}</em>
                </span>
              )}
            </div>
          )}

          {selected !== null && (
            <button
              onClick={handleNext}
              className="w-full mt-4 py-3 bg-purple-600 hover:bg-purple-700 text-white font-black rounded-2xl shadow-md transition-all active:scale-95"
            >
              {qIdx + 1 >= questions.length ? 'See Results 🏆' : 'Next Question →'}
            </button>
          )}
        </div>
      </div>
    </main>
  );
}
