'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { ArrowLeft, ArrowRight, ArrowLeftCircle, Play } from 'lucide-react';
import type { LearnCardData } from '@/lib/types';
import Mascot from '../Mascot';
import SpeakButton from '../SpeakButton';
import { bn } from '@/lib/bn';

type Accent = 'mango' | 'leaf' | 'sun';

const ACCENT: Record<Accent, { solid: string; soft: string; dot: string }> = {
  mango: { solid: 'bg-mango-500', soft: 'bg-mango-50', dot: 'bg-mango-500' },
  leaf: { solid: 'bg-leaf-500', soft: 'bg-leaf-50', dot: 'bg-leaf-500' },
  sun: { solid: 'bg-sun-500', soft: 'bg-sun-50', dot: 'bg-sun-500' },
};

/**
 * The "শেখো" (learn) step shown before the quiz. Child flips through simple
 * teaching flashcards (picture + example + one-line tip), then starts the quiz.
 */
export default function LearnPhase({
  subjectName,
  accent,
  cards,
  autoRead = false,
  backHref = '/app',
  onStartQuiz,
}: {
  subjectName: string;
  accent: Accent;
  cards: LearnCardData[];
  autoRead?: boolean;
  backHref?: string;
  onStartQuiz: () => void;
}) {
  const router = useRouter();
  const a = ACCENT[accent];
  const [index, setIndex] = useState(0);
  const [dir, setDir] = useState(1);

  const card = cards[index];
  const isLast = index === cards.length - 1;
  const readText = card ? `${card.big}. ${card.sub}. ${card.tip}` : '';

  function go(next: number) {
    setDir(next > index ? 1 : -1);
    setIndex(Math.max(0, Math.min(cards.length - 1, next)));
  }

  if (!card) {
    // No teaching content for this subject: skip straight to the quiz.
    onStartQuiz();
    return null;
  }

  return (
    <div className="mx-auto flex min-h-dvh max-w-2xl flex-col px-4 py-4 sm:px-6">
      {/* top bar */}
      <div className="flex items-center gap-3">
        <button
          onClick={() => router.push(backHref)}
          aria-label="ফিরে যাও"
          className="rounded-full p-2 text-ink-soft transition hover:bg-cream-200"
        >
          <ArrowLeft className="h-5 w-5" />
        </button>
        <div>
          <p className="text-xs font-semibold text-ink-faint">প্রথমে শেখো</p>
          <h1 className="font-heading text-lg font-extrabold text-ink">{subjectName}</h1>
        </div>
        <span className="ml-auto rounded-full bg-cream-200 px-3 py-1 text-sm font-semibold text-ink-soft">
          {bn(index + 1)} / {bn(cards.length)}
        </span>
      </div>

      {/* progress dots */}
      <div className="mt-3 flex items-center justify-center gap-1.5">
        {cards.map((c, i) => (
          <span
            key={c.id}
            className={`h-2 rounded-full transition-all ${
              i === index ? `w-6 ${a.dot}` : 'w-2 bg-cream-200'
            }`}
          />
        ))}
      </div>

      {/* mascot */}
      <div className="mt-5 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>

      {/* flashcard */}
      <div className="relative mt-4 flex-1">
        <AnimatePresence mode="wait" custom={dir}>
          <motion.div
            key={card.id}
            custom={dir}
            initial={{ opacity: 0, x: dir * 60 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: dir * -60 }}
            transition={{ duration: 0.28, ease: 'easeOut' }}
            className={`flex flex-col items-center rounded-4xl ${a.soft} px-6 py-10 text-center shadow-card`}
          >
            <div className="text-7xl" aria-hidden>
              {card.emoji}
            </div>
            <div className="mt-4 font-heading text-5xl font-extrabold text-ink">{card.big}</div>
            <div className="mt-2 font-heading text-2xl font-bold text-ink-soft">{card.sub}</div>
            <p className="mt-4 max-w-sm text-lg leading-relaxed text-ink">{card.tip}</p>
            <div className="mt-4">
              <SpeakButton key={card.id} text={readText} autoPlay={autoRead} />
            </div>
          </motion.div>
        </AnimatePresence>
      </div>

      {/* controls */}
      <div className="mt-5 flex items-center gap-3">
        <button
          onClick={() => go(index - 1)}
          disabled={index === 0}
          className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-cream-200 text-ink-soft transition active:scale-95 disabled:opacity-40"
          aria-label="আগেরটা"
        >
          <ArrowLeftCircle className="h-6 w-6" />
        </button>

        {isLast ? (
          <button
            onClick={onStartQuiz}
            className={`flex flex-1 items-center justify-center gap-2 rounded-2xl ${a.solid} px-5 py-4 text-base font-bold text-white shadow-pop transition active:scale-[0.98]`}
          >
            <Play className="h-5 w-5 fill-white" />
            চলো কুইজ খেলি!
          </button>
        ) : (
          <button
            onClick={() => go(index + 1)}
            className={`flex flex-1 items-center justify-center gap-2 rounded-2xl ${a.solid} px-5 py-4 text-base font-bold text-white shadow-pop transition active:scale-[0.98]`}
          >
            পরেরটা
            <ArrowRight className="h-5 w-5" />
          </button>
        )}
      </div>

      {/* skip to quiz */}
      {!isLast && (
        <button
          onClick={onStartQuiz}
          className="mt-3 text-center text-sm font-medium text-ink-faint transition hover:text-ink-soft"
        >
          শেখা শেষ, সরাসরি কুইজ খেলি
        </button>
      )}
    </div>
  );
}
