'use client';

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

export default function DailyChallenge({
  questions,
  alreadyDone,
  reward,
}: {
  questions: Question[];
  alreadyDone: boolean;
  reward: number;
}) {
  const router = useRouter();
  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 [finished, setFinished] = useState(false);
  const [earned, setEarned] = useState(0);

  const q = questions[index];

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

  async function next() {
    if (index + 1 >= questions.length) {
      playFinish();
      setFinished(true);
      try {
        const res = await fetch('/api/daily', { method: 'POST' });
        const data = await res.json();
        if (data.ok) setEarned(data.coinsEarned ?? 0);
      } catch {
        /* ignore */
      }
      return;
    }
    setIndex((n) => n + 1);
    setSelected(null);
    setLocked(false);
  }

  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={() => router.push('/app')}
            aria-label="ফিরে যাও"
            className="rounded-full p-2 text-ink-soft transition hover:bg-cream-200"
          >
            <ArrowLeft className="h-5 w-5" />
          </button>
          <Trophy className="h-5 w-5 text-sun-600" />
          <h1 className="font-heading text-xl font-extrabold text-ink">আজকের চ্যালেঞ্জ</h1>
        </div>
      </header>

      <main className="mx-auto max-w-2xl px-4 pt-4 sm:px-6">
        {finished || questions.length === 0 ? (
          <div className="flex flex-col items-center pt-8 text-center">
            {confetti > 0 && <Confetti key={`d-${confetti}`} pieces={40} />}
            <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)} সঠিক
            </p>
            {earned > 0 ? (
              <div className="mt-4 flex items-center gap-2 rounded-2xl bg-mango-50 px-4 py-3 font-bold text-mango-700">
                <Coins className="h-5 w-5" /> +{bn(earned)} বোনাস কয়েন!
              </div>
            ) : (
              <p className="mt-4 rounded-2xl bg-cream-100 px-4 py-3 text-sm text-ink-soft">
                {alreadyDone ? 'আজকের বোনাস আগেই নিয়েছ। কাল আবার এসো! 🌙' : ''}
              </p>
            )}
            <button
              onClick={() => router.push('/app')}
              className="mt-6 rounded-2xl bg-sun-500 px-6 py-3.5 font-bold text-white shadow-pop transition active:scale-[0.98]"
            >
              হোমে ফিরে যাও
            </button>
          </div>
        ) : (
          <>
            {alreadyDone && (
              <p className="mb-3 rounded-2xl bg-cream-100 px-4 py-2 text-center text-xs text-ink-soft">
                আজকের বোনাস আগেই নিয়েছ, তবে আবার খেলতে পারো!
              </p>
            )}
            <div className="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-sun-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" />
                {bn(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-sun-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 && (
              <button
                onClick={next}
                className="mt-5 w-full rounded-2xl bg-sun-500 px-5 py-3.5 font-bold text-white shadow-pop transition active:scale-[0.98]"
              >
                {index + 1 >= questions.length ? 'শেষ করো' : 'পরের প্রশ্ন'}
              </button>
            )}
          </>
        )}
      </main>
      <BottomNav />
    </div>
  );
}
