'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { ArrowLeft, Loader2, Check, X, RefreshCw, Star } from 'lucide-react';
import type { Question } from '@/lib/types';
import Mascot from '../Mascot';
import Confetti from '../Confetti';
import SpeakButton from '../SpeakButton';
import DemoBadge from '../DemoBadge';
import { playCorrect, playWrong, playFinish } from '@/lib/sound';
import { bn } from '@/lib/bn';

interface SubjectLite {
  id: string;
  name: string;
  emoji: string;
  accent: 'mango' | 'leaf' | 'sun';
}

type Phase = 'pick' | 'loading' | 'quiz' | 'summary';

export default function AiPractice({ subjects }: { subjects: SubjectLite[] }) {
  const router = useRouter();
  const [phase, setPhase] = useState<Phase>('pick');
  const [subject, setSubject] = useState<SubjectLite | null>(null);
  const [questions, setQuestions] = useState<Question[]>([]);
  const [index, setIndex] = useState(0);
  const [selected, setSelected] = useState<number | null>(null);
  const [locked, setLocked] = useState(false);
  const [correct, setCorrect] = useState(0);
  const [confetti, setConfetti] = useState(0);
  const [error, setError] = useState('');

  async function loadBatch(subj: SubjectLite, recentAccuracy?: number) {
    setPhase('loading');
    setError('');
    try {
      const res = await fetch('/api/ai/practice', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ subjectId: subj.id, recentAccuracy }),
      });
      const data = await res.json();
      if (res.ok && data.ok && data.questions?.length) {
        setQuestions(data.questions);
        setIndex(0);
        setSelected(null);
        setLocked(false);
        setCorrect(0);
        setPhase('quiz');
      } else {
        setError(data.error ?? 'প্রশ্ন আনা গেল না।');
        setPhase('pick');
      }
    } catch {
      setError('নেটওয়ার্ক সমস্যা, আবার চেষ্টা করো।');
      setPhase('pick');
    }
  }

  function pick(i: number) {
    if (locked) return;
    setSelected(i);
    if (i === questions[index].correctIndex) {
      playCorrect();
      setLocked(true);
      setConfetti((c) => c + 1);
      setCorrect((n) => n + 1);
    } else {
      playWrong();
      setLocked(true);
    }
  }

  function next() {
    if (index + 1 >= questions.length) {
      playFinish();
      setPhase('summary');
      return;
    }
    setIndex((n) => n + 1);
    setSelected(null);
    setLocked(false);
  }

  const q = questions[index];
  const accuracy = questions.length ? correct / questions.length : 0;

  /* ------------------------------- pick ------------------------------- */
  if (phase === 'pick') {
    return (
      <Shell onBack={() => router.push('/app/ai')}>
        <div className="flex items-center gap-3">
          <Mascot mood="happy" size={56} />
          <p className="rounded-2xl bg-white px-4 py-2 text-sm font-medium text-ink-soft shadow-card">
            কোন বিষয়ে প্র্যাকটিস করবে?
          </p>
        </div>
        {error && (
          <p className="mt-4 rounded-2xl bg-mango-50 px-4 py-3 text-center text-sm font-medium text-mango-700">
            {error}
          </p>
        )}
        <div className="mt-5 grid grid-cols-2 gap-3">
          {subjects.map((s) => (
            <button
              key={s.id}
              onClick={() => {
                setSubject(s);
                loadBatch(s);
              }}
              className="flex flex-col items-center gap-2 rounded-3xl bg-white p-5 shadow-card transition active:scale-[0.97]"
            >
              <span className="text-4xl" aria-hidden>
                {s.emoji}
              </span>
              <span className="font-heading text-lg font-bold text-ink">{s.name}</span>
            </button>
          ))}
        </div>
      </Shell>
    );
  }

  /* ----------------------------- loading ------------------------------ */
  if (phase === 'loading') {
    return (
      <Shell onBack={() => router.push('/app/ai')}>
        <div className="mt-16 flex flex-col items-center gap-3 text-ink-soft">
          <Loader2 className="h-10 w-10 animate-spin text-leaf-500" />
          তারা নতুন প্রশ্ন বানাচ্ছে…
        </div>
      </Shell>
    );
  }

  /* ----------------------------- summary ------------------------------ */
  if (phase === 'summary') {
    const pct = Math.round(accuracy * 100);
    return (
      <Shell onBack={() => router.push('/app/ai')}>
        {confetti > 0 && <Confetti key={`p-${confetti}`} pieces={36} />}
        <div className="flex flex-col items-center pt-6 text-center">
          <Mascot mood="happy" size={120} />
          <h2 className="mt-4 font-heading text-2xl font-extrabold text-ink">দারুণ প্র্যাকটিস!</h2>
          <p className="mt-1 text-ink-soft">
            {bn(correct)} / {bn(questions.length)} সঠিক ({bn(pct)}%)
          </p>
          <div className="mt-6 flex w-full max-w-xs flex-col gap-3">
            <button
              onClick={() => subject && loadBatch(subject, accuracy)}
              className="flex items-center justify-center gap-2 rounded-2xl bg-leaf-500 px-5 py-3.5 font-bold text-white shadow-pop transition active:scale-[0.98]"
            >
              <RefreshCw className="h-5 w-5" /> আরও প্র্যাকটিস
            </button>
            <button
              onClick={() => setPhase('pick')}
              className="rounded-2xl bg-cream-200 px-5 py-3.5 font-bold text-ink-soft transition active:scale-[0.98]"
            >
              অন্য বিষয়
            </button>
          </div>
        </div>
      </Shell>
    );
  }

  /* ------------------------------- quiz ------------------------------- */
  return (
    <Shell onBack={() => router.push('/app/ai')}>
      {confetti > 0 && locked && selected === q.correctIndex && <Confetti key={`c-${confetti}`} />}
      <div className="mt-2 flex items-center gap-2">
        <div className="h-3 flex-1 overflow-hidden rounded-full bg-cream-200">
          <div
            className="h-full rounded-full bg-leaf-500 transition-all"
            style={{ width: `${((index + (locked ? 1 : 0)) / questions.length) * 100}%` }}
          />
        </div>
        <span className="flex items-center gap-1 text-sm font-bold text-sun-600">
          <Star className="h-4 w-4 fill-sun-500 text-sun-500" />
          {correct}
        </span>
      </div>

      <div className="mt-5 flex items-start gap-3">
        <Mascot mood={locked ? (selected === q.correctIndex ? 'happy' : 'sad') : 'idle'} size={56} />
        <motion.div
          key={q.id}
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex-1 rounded-3xl bg-white p-5 shadow-card"
        >
          <div className="flex items-start justify-between gap-2">
            <p className="text-xs font-semibold text-ink-faint">
              প্রশ্ন {bn(index + 1)} / {bn(questions.length)}
            </p>
            <SpeakButton key={q.id} text={q.question} size="sm" />
          </div>
          <h2 className="mt-1 font-heading text-xl font-bold leading-snug text-ink">{q.question}</h2>
        </motion.div>
      </div>

      <div className="mt-5 grid gap-3 sm:grid-cols-2">
        {q.options.map((opt, i) => {
          const isCorrect = locked && i === q.correctIndex;
          const isWrong = locked && selected === i && i !== q.correctIndex;
          return (
            <button
              key={i}
              disabled={locked}
              onClick={() => pick(i)}
              className={`flex min-h-[56px] items-center justify-between gap-2 rounded-2xl border-2 px-4 py-3.5 text-left text-lg font-semibold transition ${
                isCorrect
                  ? 'border-leaf-500 bg-leaf-50 text-leaf-700'
                  : isWrong
                    ? 'border-mango-500 bg-mango-50 text-mango-700'
                    : 'border-cream-200 bg-white text-ink hover:border-leaf-500'
              }`}
            >
              <span>{opt}</span>
              {isCorrect && <Check className="h-6 w-6 text-leaf-600" />}
              {isWrong && <X className="h-6 w-6 text-mango-600" />}
            </button>
          );
        })}
      </div>

      {locked && (
        <div className="mt-5">
          {q.explanation && (
            <p className="mb-3 rounded-2xl bg-leaf-50 px-4 py-3 text-center text-sm font-medium text-leaf-700">
              {q.explanation}
            </p>
          )}
          <button
            onClick={next}
            className="flex w-full items-center justify-center gap-2 rounded-2xl bg-leaf-500 px-5 py-3.5 font-bold text-white shadow-pop transition active:scale-[0.98]"
          >
            {index + 1 >= questions.length ? 'শেষ করো' : 'পরের প্রশ্ন'}
          </button>
        </div>
      )}
    </Shell>
  );
}

function Shell({ children, onBack }: { children: React.ReactNode; onBack: () => void }) {
  return (
    <div className="min-h-dvh pb-24 lg:pb-0 lg:pl-24">
      <header className="sticky top-0 z-30 bg-cream/90 px-4 pb-3 pt-4 backdrop-blur sm:px-6">
        <div className="mx-auto flex max-w-2xl items-center gap-3">
          <button
            onClick={onBack}
            aria-label="ফিরে যাও"
            className="rounded-full p-2 text-ink-soft transition hover:bg-cream-200"
          >
            <ArrowLeft className="h-5 w-5" />
          </button>
          <h1 className="font-heading text-xl font-extrabold text-ink">অসীম প্র্যাকটিস</h1>
          <DemoBadge className="ml-auto" />
        </div>
      </header>
      <main className="mx-auto max-w-2xl px-4 pt-4 sm:px-6">{children}</main>
    </div>
  );
}
