'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { ArrowLeft, Lock, Star, Check, Play, Puzzle } from 'lucide-react';
import BottomNav from './BottomNav';
import Mascot from '../Mascot';
import { bn } from '@/lib/bn';

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

interface LevelNode {
  id: string;
  index: number;
  title: string;
  subtitle: string;
  locked: boolean;
  completed: boolean;
  bestStars: number;
  questionCount: number;
}

const ACCENT: Record<Accent, { solid: string; soft: string; text: string; ring: string }> = {
  mango: { solid: 'bg-mango-500', soft: 'bg-mango-50', text: 'text-mango-700', ring: 'ring-mango-200' },
  leaf: { solid: 'bg-leaf-500', soft: 'bg-leaf-50', text: 'text-leaf-700', ring: 'ring-leaf-200' },
  sun: { solid: 'bg-sun-500', soft: 'bg-sun-50', text: 'text-sun-600', ring: 'ring-sun-200' },
};

export default function LevelMap({
  subjectId,
  subjectName,
  accent,
  emoji,
  hasMatchGame,
  levels,
}: {
  subjectId: string;
  subjectName: string;
  accent: Accent;
  emoji: string;
  hasMatchGame: boolean;
  levels: LevelNode[];
}) {
  const router = useRouter();
  const a = ACCENT[accent];

  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>
          <span className="text-2xl" aria-hidden>
            {emoji}
          </span>
          <div>
            <h1 className="font-heading text-xl font-extrabold text-ink">{subjectName}</h1>
            <p className="text-xs text-ink-soft">
              {bn(levels.filter((l) => l.completed).length)} / {bn(levels.length)} লেভেল শেষ
            </p>
          </div>
        </div>
      </header>

      <main className="mx-auto max-w-2xl px-4 pt-4 sm:px-6">
        {/* winding path of levels */}
        <ol className="relative mx-auto flex max-w-md flex-col gap-4">
          {levels.map((lvl, i) => {
            const align = i % 2 === 0 ? 'self-start' : 'self-end';
            return (
              <motion.li
                key={lvl.id}
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: i * 0.05 }}
                className={`w-[78%] ${align}`}
              >
                <LevelCard node={lvl} accent={a} subjectId={subjectId} />
              </motion.li>
            );
          })}
        </ol>

        {hasMatchGame && (
          <Link
            href="/app/game"
            className="mt-6 flex items-center justify-center gap-2 rounded-2xl bg-white px-5 py-3.5 font-bold text-ink shadow-card transition active:scale-[0.98]"
          >
            <Puzzle className="h-5 w-5 text-leaf-600" /> ম্যাচিং গেম খেলো
          </Link>
        )}

        <div className="mt-8 flex justify-center">
          <Mascot mood="happy" size={72} />
        </div>
      </main>

      <BottomNav />
    </div>
  );
}

function LevelCard({
  node,
  accent,
  subjectId,
}: {
  node: LevelNode;
  accent: { solid: string; soft: string; text: string; ring: string };
  subjectId: string;
}) {
  const inner = (
    <div
      className={`flex items-center gap-3 rounded-3xl p-4 shadow-card transition ${
        node.locked ? 'bg-cream-100' : node.completed ? accent.soft : 'bg-white'
      } ${!node.locked ? 'active:scale-[0.98]' : ''}`}
    >
      <div
        className={`flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl font-heading text-lg font-extrabold ${
          node.locked
            ? 'bg-cream-200 text-ink-faint'
            : node.completed
              ? `${accent.solid} text-white`
              : `${accent.solid} text-white`
        }`}
      >
        {node.locked ? (
          <Lock className="h-5 w-5" />
        ) : node.completed ? (
          <Check className="h-6 w-6" />
        ) : (
          <Play className="h-5 w-5 fill-white" />
        )}
      </div>
      <div className="flex-1">
        <p className="font-heading text-base font-bold text-ink">{node.title}</p>
        <p className="text-xs text-ink-soft">
          {node.locked ? 'আগেরটা শেষ করো' : node.subtitle}
        </p>
      </div>
      {node.completed && (
        <div className="flex items-center gap-0.5">
          {Array.from({ length: 3 }).map((_, s) => (
            <Star
              key={s}
              className={`h-4 w-4 ${s < node.bestStars ? 'fill-sun-500 text-sun-500' : 'text-cream-200'}`}
            />
          ))}
        </div>
      )}
    </div>
  );

  if (node.locked) return <div aria-disabled>{inner}</div>;
  return <Link href={`/app/lesson/${subjectId}/${node.id}`}>{inner}</Link>;
}
