"use client";

import { useEffect, useState } from "react";
import { motion } from "framer-motion";
import { CalendarCheck2, CheckCircle2, Clock3, Users } from "lucide-react";
import AnimatedNumber from "@/components/ppdb/AnimatedNumber";
import { jurusanName, STATUS_LABEL } from "@/lib/jurusan";

interface StatsData {
  total: number;
  today: number;
  statusCount: Record<string, number>;
  perJurusan: { code: string; name: string; kuota: number; count: number }[];
  perDay: { date: string; count: number }[];
  recent: { id: string; regNumber: string; fullName: string; jurusan: string; status: string; createdAt: string }[];
}

const STATUS_COLORS: Record<string, string> = {
  MENUNGGU: "#f59e0b",
  DITERIMA: "#10b981",
  CADANGAN: "#0ea5e9",
  DITOLAK: "#ef4444",
};

const BAR_COLORS = ["#7B1E28", "#D4A017", "#a32838", "#8a6a10"];

export default function AdminStats() {
  const [stats, setStats] = useState<StatsData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/admin/stats")
      .then((r) => (r.ok ? r.json() : null))
      .then((d) => setStats(d))
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {[0, 1, 2, 3].map((i) => (
          <div key={i} className="h-28 animate-pulse rounded-3xl bg-white/70" />
        ))}
      </div>
    );
  }
  if (!stats) return <p className="text-sm text-muted-foreground">Gagal memuat statistik.</p>;

  const cards = [
    { label: "Total Pendaftar", value: stats.total, Icon: Users, color: "bg-[#7B1E28]/10 text-[#7B1E28]" },
    { label: "Hari Ini", value: stats.today, Icon: CalendarCheck2, color: "bg-[#D4A017]/15 text-[#8a6a10]" },
    { label: "Diterima", value: stats.statusCount.DITERIMA || 0, Icon: CheckCircle2, color: "bg-emerald-100 text-emerald-700" },
    { label: "Menunggu Verifikasi", value: stats.statusCount.MENUNGGU || 0, Icon: Clock3, color: "bg-amber-100 text-amber-700" },
  ];

  // Donut
  const donutOrder = ["MENUNGGU", "DITERIMA", "CADANGAN", "DITOLAK"];
  const donutTotal = donutOrder.reduce((a, k) => a + (stats.statusCount[k] || 0), 0);
  const R = 42;
  const C = 2 * Math.PI * R;
  let acc = 0;

  // Tren
  const W = 600;
  const H = 180;
  const max = Math.max(1, ...stats.perDay.map((p) => p.count));
  const pts = stats.perDay.map((p, i) => ({
    x: (i / Math.max(1, stats.perDay.length - 1)) * W,
    y: H - 16 - (p.count / max) * (H - 46),
    ...p,
  }));
  const line = pts.map((p, i) => `${i === 0 ? "M" : "L"}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(" ");
  const area = `${line} L${W},${H} L0,${H} Z`;

  return (
    <div className="space-y-6">
      {/* kartu statistik */}
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
        {cards.map((c, i) => (
          <motion.div
            key={c.label}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.4, delay: i * 0.08 }}
            whileHover={{ y: -4 }}
            className="rounded-3xl border bg-card p-5 shadow-sm"
          >
            <div className="flex items-center justify-between">
              <span className={`grid size-11 place-items-center rounded-2xl ${c.color}`}>
                <c.Icon className="size-5" />
              </span>
            </div>
            <AnimatedNumber value={c.value} className="mt-3 block text-3xl font-extrabold text-[#4a1520]" />
            <p className="mt-1 text-sm text-muted-foreground">{c.label}</p>
          </motion.div>
        ))}
      </div>

      <div className="grid gap-4 lg:grid-cols-3">
        {/* bar per jurusan */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.45, delay: 0.15 }}
          className="rounded-3xl border bg-card p-6 shadow-sm lg:col-span-2"
        >
          <h3 className="text-base font-bold text-[#4a1520]">Pendaftar per Program Keahlian</h3>
          <div className="mt-5 space-y-4">
            {stats.perJurusan.map((j, i) => {
              const pct = Math.min(100, Math.round((j.count / Math.max(1, j.kuota)) * 100));
              return (
                <div key={j.code}>
                  <div className="mb-1.5 flex items-center justify-between text-sm">
                    <span className="font-semibold text-[#4a1520]">{j.name}</span>
                    <span className="text-muted-foreground">
                      <b className="text-[#7B1E28]">{j.count}</b> / {j.kuota} kuota
                    </span>
                  </div>
                  <div className="h-3 overflow-hidden rounded-full bg-muted">
                    <motion.div
                      initial={{ width: 0 }}
                      animate={{ width: `${pct}%` }}
                      transition={{ duration: 1, delay: 0.3 + i * 0.12, ease: "easeOut" }}
                      className="h-full rounded-full"
                      style={{ background: `linear-gradient(90deg, ${BAR_COLORS[i]}, ${BAR_COLORS[i]}cc)` }}
                    />
                  </div>
                </div>
              );
            })}
          </div>

          {/* tren harian */}
          <h3 className="mt-8 text-base font-bold text-[#4a1520]">Tren Pendaftar 14 Hari Terakhir</h3>
          <div className="mt-4 overflow-x-auto ppdb-scrollbar">
            <svg viewBox={`0 0 ${W} ${H}`} className="h-44 w-full min-w-[520px]" preserveAspectRatio="none" role="img" aria-label="Grafik tren pendaftar harian">
              <defs>
                <linearGradient id="trendFill" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="0%" stopColor="#D4A017" stopOpacity="0.5" />
                  <stop offset="100%" stopColor="#7B1E28" stopOpacity="0.05" />
                </linearGradient>
              </defs>
              {[0.25, 0.5, 0.75].map((g) => (
                <line key={g} x1="0" x2={W} y1={H - 16 - g * (H - 46)} y2={H - 16 - g * (H - 46)} stroke="#7B1E28" strokeOpacity="0.08" />
              ))}
              <motion.path
                d={area}
                fill="url(#trendFill)"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ duration: 1, delay: 0.6 }}
              />
              <motion.path
                d={line}
                fill="none"
                stroke="#7B1E28"
                strokeWidth="2.5"
                strokeLinecap="round"
                initial={{ pathLength: 0 }}
                animate={{ pathLength: 1 }}
                transition={{ duration: 1.4, delay: 0.4, ease: "easeInOut" }}
              />
              {pts.map((p, i) => (
                <motion.circle
                  key={i}
                  cx={p.x}
                  cy={p.y}
                  r="3.5"
                  fill="#D4A017"
                  stroke="#7B1E28"
                  strokeWidth="1.5"
                  initial={{ scale: 0 }}
                  animate={{ scale: 1 }}
                  transition={{ delay: 0.5 + i * 0.06 }}
                />
              ))}
            </svg>
          </div>
          <div className="mt-1 flex justify-between text-xs text-muted-foreground">
            <span>{stats.perDay[0]?.date.split("-").reverse().join("/")}</span>
            <span>{stats.perDay[stats.perDay.length - 1]?.date.split("-").reverse().join("/")}</span>
          </div>
        </motion.div>

        {/* donut status + terbaru */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.45, delay: 0.25 }}
          className="flex flex-col gap-4"
        >
          <div className="rounded-3xl border bg-card p-6 shadow-sm">
            <h3 className="text-base font-bold text-[#4a1520]">Status Verifikasi</h3>
            <div className="mt-4 flex items-center justify-center">
              <svg viewBox="0 0 120 120" className="size-40 -rotate-90" role="img" aria-label="Diagram status verifikasi">
                <circle cx="60" cy="60" r={R} fill="none" stroke="#f1e9df" strokeWidth="14" />
                {donutOrder.map((k) => {
                  const val = stats.statusCount[k] || 0;
                  if (val === 0 || donutTotal === 0) return null;
                  const frac = val / donutTotal;
                  const len = frac * C;
                  const el = (
                    <motion.circle
                      key={k}
                      cx="60"
                      cy="60"
                      r={R}
                      fill="none"
                      stroke={STATUS_COLORS[k]}
                      strokeWidth="14"
                      strokeDasharray={`${len} ${C - len}`}
                      strokeDashoffset={-acc}
                      strokeLinecap="butt"
                      initial={{ opacity: 0 }}
                      animate={{ opacity: 1 }}
                      transition={{ duration: 0.8, delay: 0.3 }}
                    />
                  );
                  acc += len;
                  return el;
                })}
              </svg>
            </div>
            <div className="mt-3 grid grid-cols-2 gap-2">
              {donutOrder.map((k) => (
                <div key={k} className="flex items-center gap-2 text-xs">
                  <span className="size-3 rounded-sm" style={{ background: STATUS_COLORS[k] }} />
                  <span className="text-muted-foreground">{STATUS_LABEL[k]}</span>
                  <b className="ml-auto text-[#4a1520]">{stats.statusCount[k] || 0}</b>
                </div>
              ))}
            </div>
          </div>

          <div className="flex-1 rounded-3xl border bg-card p-6 shadow-sm">
            <h3 className="text-base font-bold text-[#4a1520]">Pendaftar Terbaru</h3>
            <div className="mt-3 space-y-2.5">
              {stats.recent.length === 0 && (
                <p className="text-sm text-muted-foreground">Belum ada pendaftar.</p>
              )}
              {stats.recent.map((r) => (
                <div key={r.id} className="flex items-center gap-3 rounded-xl bg-muted/60 px-3 py-2.5">
                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-semibold text-[#4a1520]">{r.fullName}</p>
                    <p className="text-xs text-muted-foreground">
                      {r.regNumber} • {jurusanName(r.jurusan)}
                    </p>
                  </div>
                  <span
                    className="size-2.5 shrink-0 rounded-full"
                    style={{ background: STATUS_COLORS[r.status] || "#ccc" }}
                    title={STATUS_LABEL[r.status]}
                  />
                </div>
              ))}
            </div>
          </div>
        </motion.div>
      </div>
    </div>
  );
}
