'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 { Word } from '@/types';

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

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

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

/**
 * Produce a plausible misspelling of `word`.
 * Tries multiple strategies and guarantees the result ≠ original.
 */
function createMisspelling(word: string): string {
  const vowels = 'aeiou';

  const strategies: Array<() => string> = [
    // Swap two adjacent letters
    () => {
      const i = Math.floor(Math.random() * (word.length - 1));
      return word.slice(0, i) + word[i + 1] + word[i] + word.slice(i + 2);
    },
    // Replace a vowel with a different vowel
    () => {
      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 alt = vowels.replace(word[i], '');
      return word.slice(0, i) + alt[Math.floor(Math.random() * alt.length)] + word.slice(i + 1);
    },
    // Drop one interior letter
    () => {
      const i = 1 + Math.floor(Math.random() * (word.length - 1));
      return word.slice(0, i) + word.slice(i + 1);
    },
    // Double a consonant (adds incorrect double)
    () => {
      const indices = [...word]
        .map((c, i) => (!vowels.includes(c) ? i : -1))
        .filter(i => i > 0 && i < word.length - 1);
      if (!indices.length) return word + word[word.length - 1];
      const i = indices[Math.floor(Math.random() * indices.length)];
      return word.slice(0, i) + word[i] + word.slice(i);
    },
    // Swap a vowel's position with an adjacent consonant
    () => {
      const indices = [...word]
        .map((c, i) => (vowels.includes(c) && i > 0 ? 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 - 1) + word[i] + word[i - 1] + word.slice(i + 1);
    },
  ];

  let result = word;
  let attempts = 0;
  while ((result === word || result.length === 0) && attempts < 20) {
    result = strategies[Math.floor(Math.random() * strategies.length)]();
    attempts++;
  }

  // ultimate fallback
  if (result === word || result.length === 0) {
    const lastChar = word[word.length - 1];
    result = word.slice(0, -1) + (lastChar === 'e' ? 'a' : 'e');
  }

  return result;
}

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',
};

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

export default function TypePage() {
  const { progress, recordAttempt } = useProgress();

  const [bank,  setBank]  = useState<Bank>('everyday');
  const [level, setLevel] = useState<Level>('copy');
  const [words, setWords] = useState<Word[]>([]);
  const [idx,   setIdx]   = useState(0);

  const [misspelling,     setMisspelling]     = useState('');
  const [input,           setInput]           = useState('');
  const [status,          setStatus]          = useState<Status>('idle');
  const [sessionCorrect,  setSessionCorrect]  = useState(0);
  const [sessionTotal,    setSessionTotal]    = useState(0);

  const inputRef = useRef<HTMLInputElement>(null);
  const current  = words[idx];

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

  // Re-generate misspelling when the word or level changes
  useEffect(() => {
    if (current && level === 'fix') {
      setMisspelling(createMisspelling(current.word));
    }
    setInput('');
    setStatus('idle');
  }, [current, level]);

  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');
    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-orange-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-orange-50 via-amber-50 to-yellow-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-orange-600 hover:text-orange-800 font-bold text-lg">
            ← Back
          </Link>
          <h1 className="text-2xl font-black text-orange-700">Write 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-orange-100 p-1 gap-1 mb-3 shadow-sm">
          <button
            onClick={() => setBank('everyday')}
            className={`flex-1 py-2.5 rounded-xl text-sm font-bold transition-all ${
              bank === 'everyday'
                ? 'bg-orange-500 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>

        {/* ── Level toggle ─────────────────────────────────────────────── */}
        <div className="flex bg-white rounded-2xl border-2 border-orange-100 p-1 gap-1 mb-4 shadow-sm">
          <button
            onClick={() => setLevel('copy')}
            className={`flex-1 py-2.5 px-3 rounded-xl text-sm font-bold transition-all ${
              level === 'copy'
                ? 'bg-green-500 text-white shadow'
                : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            📋 Level 1 — Copy It
          </button>
          <button
            onClick={() => setLevel('fix')}
            className={`flex-1 py-2.5 px-3 rounded-xl text-sm font-bold transition-all ${
              level === 'fix'
                ? 'bg-red-500 text-white shadow'
                : 'text-gray-500 hover:text-gray-700'
            }`}
          >
            🔧 Level 2 — Fix It!
          </button>
        </div>

        {/* Level description hint */}
        <p className="text-center text-sm font-semibold text-gray-400 mb-4">
          {level === 'copy'
            ? '📋 The word is shown — type it exactly as you see it'
            : '🔧 The word has a mistake — find it and type it correctly'}
        </p>

        {/* Session score */}
        <div className="bg-white rounded-2xl px-4 py-3 mb-4 shadow-sm flex items-center gap-2 border border-orange-100">
          <span className="text-xl">⭐</span>
          <span className="font-bold text-orange-700 text-sm">
            {sessionCorrect} / {sessionTotal} correct this session
          </span>
        </div>

        {/* ── Main 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'   :
            level === 'copy'       ? 'border-green-200' : 'border-red-200'
          }`}
        >
          {/* Badges row */}
          <div className="flex items-center gap-2 mb-4 flex-wrap">
            <span className="bg-orange-100 text-orange-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 + example */}
          <p className="text-gray-700 font-semibold mb-1 leading-relaxed text-sm">
            📖 {current.definition}
          </p>
          <p className="text-gray-400 text-sm italic mb-5">
            &ldquo;{current.example}&rdquo;
          </p>

          {/* ── Level 1: show the correct word ── */}
          {level === 'copy' && status === 'idle' && (
            <div className="bg-green-50 rounded-2xl p-5 mb-5 text-center border-2 border-green-200">
              <p className="text-xs font-black text-green-500 uppercase tracking-widest mb-3">
                📋 Copy this word exactly:
              </p>
              <p className="text-5xl font-black text-green-700 tracking-wider select-none">
                {current.word}
              </p>
            </div>
          )}

          {/* ── Level 2: show the misspelled word ── */}
          {level === 'fix' && status === 'idle' && (
            <div className="bg-red-50 rounded-2xl p-5 mb-5 border-2 border-red-200">
              <p className="text-xs font-black text-red-400 uppercase tracking-widest text-center mb-3">
                🔧 This word has a spelling mistake:
              </p>
              <p className="text-5xl font-black text-red-500 tracking-wider text-center select-none">
                {misspelling}
              </p>
              <p className="text-xs text-center text-red-300 font-semibold mt-3">
                Type the correct version in the box below
              </p>
            </div>
          )}

          {/* Input + submit */}
          {status === 'idle' && (
            <div>
              <input
                ref={inputRef}
                type="text"
                value={input}
                onChange={e => setInput(e.target.value)}
                onKeyDown={handleKey}
                placeholder={
                  level === 'copy'
                    ? 'Type the word above…'
                    : 'Type the correct spelling…'
                }
                autoComplete="off"
                autoCorrect="off"
                autoCapitalize="off"
                spellCheck={false}
                className="w-full border-2 border-orange-200 rounded-2xl px-4 py-3 text-lg font-bold text-gray-800 focus:outline-none focus:border-orange-500 placeholder-gray-300"
              />
              <button
                onClick={handleSubmit}
                disabled={!input.trim()}
                className="w-full mt-4 py-3 rounded-2xl font-black text-lg bg-orange-500 hover:bg-orange-600 text-white shadow-md disabled:opacity-40 disabled:cursor-not-allowed transition-all active:scale-95"
              >
                Check ✓
              </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-600 font-black text-2xl tracking-wider mt-2">
                    {current.word}
                  </p>
                  {level === 'fix' && (
                    <p className="text-green-400 text-sm font-semibold mt-1">
                      You spotted and fixed the mistake!
                    </p>
                  )}
                </>
              ) : (
                <>
                  <p className="text-5xl mb-2">😅</p>
                  <p className="text-xl font-black text-red-600">Not quite!</p>
                  {level === 'fix' && (
                    <p className="text-gray-500 text-sm font-semibold mt-1">
                      The misspelled word was:{' '}
                      <span className="text-red-400 font-black">{misspelling}</span>
                    </p>
                  )}
                  <p className="text-gray-600 font-semibold mt-1">
                    Correct spelling:{' '}
                    <span className="text-red-600 font-black text-xl">{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-orange-500 hover:bg-orange-600 text-white font-black rounded-2xl shadow-md transition-all active:scale-95"
              >
                Next Word →
              </button>
            </div>
          )}
        </div>
      </div>
    </main>
  );
}
