"use client";

import { useCallback, useEffect, useState } from "react";
import { motion } from "framer-motion";
import {
  ChevronLeft,
  ChevronRight,
  Download,
  FileText,
  ImageIcon,
  MessageCircle,
  Search,
  Loader2,
} from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { JURUSAN, jurusanName, STATUS_LABEL, STATUS_LIST } from "@/lib/jurusan";
import { waLink } from "@/lib/usePublic";
import type { AdminRegistration } from "@/lib/types";

const JURUSAN_BADGE: Record<string, string> = {
  OTOMOTIF: "bg-amber-100 text-amber-800 border-amber-300",
  TKJ: "bg-sky-100 text-sky-800 border-sky-300",
  MPLB: "bg-emerald-100 text-emerald-800 border-emerald-300",
  DKV: "bg-pink-100 text-pink-800 border-pink-300",
};

function fmtDate(iso: string) {
  return new Date(iso).toLocaleString("id-ID", { dateStyle: "medium", timeStyle: "short" });
}

export default function AdminTable() {
  const [items, setItems] = useState<AdminRegistration[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(10);
  const [q, setQ] = useState("");
  const [qDebounced, setQDebounced] = useState("");
  const [status, setStatus] = useState("all");
  const [jurusan, setJurusan] = useState("all");
  const [loading, setLoading] = useState(true);
  const [detailId, setDetailId] = useState<string | null>(null);
  const [detail, setDetail] = useState<AdminRegistration | null>(null);
  const [patchStatus, setPatchStatus] = useState("");
  const [patchCatatan, setPatchCatatan] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    const t = setTimeout(() => setQDebounced(q), 400);
    return () => clearTimeout(t);
  }, [q]);

  const load = useCallback(() => {
    setLoading(true);
    const params = new URLSearchParams({
      q: qDebounced,
      status: status === "all" ? "" : status,
      jurusan: jurusan === "all" ? "" : jurusan,
      page: String(page),
      pageSize: String(pageSize),
    });
    fetch(`/api/admin/registrations?${params}`)
      .then((r) => (r.ok ? r.json() : { items: [], total: 0 }))
      .then((d) => {
        setItems(d.items || []);
        setTotal(d.total || 0);
      })
      .finally(() => setLoading(false));
  }, [qDebounced, status, jurusan, page, pageSize]);

  useEffect(load, [load]);

  const openDetail = async (id: string) => {
    setDetailId(id);
    const res = await fetch(`/api/admin/registrations/${id}`);
    if (res.ok) {
      const d = await res.json();
      setDetail(d.item);
      setPatchStatus(d.item.status);
      setPatchCatatan(d.item.catatan || "");
    }
  };

  const saveDetail = async () => {
    if (!detail) return;
    setSaving(true);
    try {
      const res = await fetch(`/api/admin/registrations/${detail.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: patchStatus, catatan: patchCatatan }),
      });
      const json = await res.json();
      if (!res.ok) {
        toast.error(json.error || "Gagal menyimpan.");
        return;
      }
      toast.success(`Pendaftaran ${detail.regNumber} diperbarui.`);
      setDetail(json.item);
      load();
    } catch {
      toast.error("Terjadi kesalahan jaringan.");
    } finally {
      setSaving(false);
    }
  };

  const pages = Math.max(1, Math.ceil(total / pageSize));

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4 }}
      className="space-y-4"
    >
      {/* toolbar */}
      <div className="flex flex-col gap-3 rounded-3xl border bg-card p-4 shadow-sm sm:flex-row sm:items-center">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            value={q}
            onChange={(e) => {
              setQ(e.target.value);
              setPage(1);
            }}
            placeholder="Cari nomor registrasi, nama, NISN, atau asal sekolah…"
            className="h-11 rounded-xl pl-9"
          />
        </div>
        <div className="flex gap-2">
          <Select
            value={status}
            onValueChange={(v) => {
              setStatus(v);
              setPage(1);
            }}
          >
            <SelectTrigger className="h-11 w-full rounded-xl sm:w-44">
              <SelectValue placeholder="Status" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Semua Status</SelectItem>
              {STATUS_LIST.map((s) => (
                <SelectItem key={s} value={s}>
                  {STATUS_LABEL[s]}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Select
            value={jurusan}
            onValueChange={(v) => {
              setJurusan(v);
              setPage(1);
            }}
          >
            <SelectTrigger className="h-11 w-full rounded-xl sm:w-52">
              <SelectValue placeholder="Jurusan" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">Semua Jurusan</SelectItem>
              {JURUSAN.map((j) => (
                <SelectItem key={j.code} value={j.code}>
                  {j.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <a href="/api/admin/export" download>
            <Button className="h-11 gap-1.5 rounded-xl bg-[#D4A017] text-[#4a121c] font-semibold hover:bg-[#F0B429]">
              <Download className="size-4" /> Export
            </Button>
          </a>
        </div>
      </div>

      {/* tabel */}
      <div className="overflow-hidden rounded-3xl border bg-card shadow-sm">
        <div className="overflow-x-auto ppdb-scrollbar">
          <table className="w-full min-w-[760px] text-sm">
            <thead>
              <tr className="border-b bg-muted/60 text-left text-xs uppercase tracking-wide text-muted-foreground">
                <th className="px-4 py-3 font-semibold">No. Registrasi</th>
                <th className="px-4 py-3 font-semibold">Nama</th>
                <th className="px-4 py-3 font-semibold">Jurusan</th>
                <th className="px-4 py-3 font-semibold">Asal Sekolah</th>
                <th className="px-4 py-3 font-semibold">Status</th>
                <th className="px-4 py-3 font-semibold">Waktu Daftar</th>
                <th className="px-4 py-3 font-semibold text-right">Aksi</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={7} className="px-4 py-10 text-center text-muted-foreground">
                    <Loader2 className="mx-auto size-6 animate-spin" />
                  </td>
                </tr>
              ) : items.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-4 py-10 text-center text-muted-foreground">
                    Tidak ada data pendaftar yang cocok.
                  </td>
                </tr>
              ) : (
                items.map((r) => (
                  <tr key={r.id} className="border-b transition-colors last:border-0 hover:bg-[#fdf6ec]">
                    <td className="px-4 py-3 font-bold tabular-nums text-[#7B1E28]">{r.regNumber}</td>
                    <td className="px-4 py-3">
                      <p className="font-semibold text-[#4a1520]">{r.fullName}</p>
                      <p className="text-xs text-muted-foreground">NISN {r.nisn}</p>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`inline-block rounded-full border px-2.5 py-1 text-xs font-semibold ${JURUSAN_BADGE[r.jurusan] || ""}`}>
                        {r.jurusan}
                      </span>
                    </td>
                    <td className="max-w-44 truncate px-4 py-3 text-muted-foreground">{r.asalSekolah}</td>
                    <td className="px-4 py-3">
                      <span className={`inline-block rounded-full border px-2.5 py-1 text-xs font-semibold ${STATUS_LABEL_COLOR(r.status)}`}>
                        {STATUS_LABEL[r.status] || r.status}
                      </span>
                    </td>
                    <td className="whitespace-nowrap px-4 py-3 text-xs text-muted-foreground">{fmtDate(r.createdAt)}</td>
                    <td className="px-4 py-3 text-right">
                      <Button
                        variant="outline"
                        size="sm"
                        className="rounded-full border-[#7B1E28]/30 text-[#7B1E28] hover:bg-[#7B1E28] hover:text-white"
                        onClick={() => openDetail(r.id)}
                      >
                        Detail
                      </Button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        <div className="flex flex-wrap items-center justify-between gap-2 border-t bg-muted/30 px-4 py-3 text-sm">
          <span className="text-muted-foreground">
            {total} pendaftar — halaman {page} dari {pages}
          </span>
          <div className="flex gap-2">
            <Button
              variant="outline"
              size="sm"
              className="gap-1 rounded-full"
              disabled={page <= 1}
              onClick={() => setPage((p) => Math.max(1, p - 1))}
            >
              <ChevronLeft className="size-4" /> Sebelumnya
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="gap-1 rounded-full"
              disabled={page >= pages}
              onClick={() => setPage((p) => Math.min(pages, p + 1))}
            >
              Berikutnya <ChevronRight className="size-4" />
            </Button>
          </div>
        </div>
      </div>

      {/* sheet detail */}
      <Sheet open={!!detailId} onOpenChange={(o) => !o && setDetailId(null)}>
        <SheetContent className="w-full overflow-y-auto ppdb-scrollbar sm:max-w-xl" side="right">
          {detail && (
            <>
              <SheetHeader>
                <SheetTitle className="text-left text-xl text-[#4a1520]">{detail.fullName}</SheetTitle>
                <SheetDescription className="text-left">
                  {detail.regNumber} • {jurusanName(detail.jurusan)} • daftar {fmtDate(detail.createdAt)}
                </SheetDescription>
              </SheetHeader>

              <div className="mt-4 space-y-5 pb-6">
                <section className="rounded-2xl border p-4">
                  <h4 className="mb-3 text-sm font-bold uppercase tracking-wide text-[#8a6a10]">Data Pribadi</h4>
                  <dl className="grid grid-cols-[40%_1fr] gap-y-2 text-sm">
                    <dt className="text-muted-foreground">NISN</dt>
                    <dd className="font-medium">{detail.nisn}</dd>
                    <dt className="text-muted-foreground">Jenis Kelamin</dt>
                    <dd className="font-medium">{detail.gender === "L" ? "Laki-laki" : "Perempuan"}</dd>
                    <dt className="text-muted-foreground">Tempat/Tgl Lahir</dt>
                    <dd className="font-medium">
                      {detail.birthPlace}, {new Date(detail.birthDate).toLocaleDateString("id-ID", { dateStyle: "long" })}
                    </dd>
                    <dt className="text-muted-foreground">Agama</dt>
                    <dd className="font-medium">{detail.religion}</dd>
                    <dt className="text-muted-foreground">Alamat</dt>
                    <dd className="font-medium break-words">{detail.address}</dd>
                  </dl>
                </section>

                <section className="rounded-2xl border p-4">
                  <h4 className="mb-3 text-sm font-bold uppercase tracking-wide text-[#8a6a10]">Orang Tua & Sekolah</h4>
                  <dl className="grid grid-cols-[40%_1fr] gap-y-2 text-sm">
                    <dt className="text-muted-foreground">Nama Ayah</dt>
                    <dd className="font-medium">{detail.namaAyah}</dd>
                    <dt className="text-muted-foreground">Nama Ibu</dt>
                    <dd className="font-medium">{detail.namaIbu}</dd>
                    <dt className="text-muted-foreground">HP Orang Tua</dt>
                    <dd className="font-medium">{detail.noHpOrangTua}</dd>
                    <dt className="text-muted-foreground">WA Siswa</dt>
                    <dd className="font-medium">{detail.noWaSiswa || "-"}</dd>
                    <dt className="text-muted-foreground">Asal Sekolah</dt>
                    <dd className="font-medium">{detail.asalSekolah}</dd>
                    <dt className="text-muted-foreground">Tahun Lulus</dt>
                    <dd className="font-medium">{detail.tahunLulus}</dd>
                  </dl>
                  <a
                    href={waLink(
                      detail.noWaSiswa || detail.noHpOrangTua,
                      `Halo ${detail.namaAyah ? "Bapak/Ibu" : ""} dari ${detail.fullName} (${detail.regNumber}), kami dari panitia PPDB SMK Al Aitaam ingin menyampaikan informasi pendaftaran.`
                    )}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="mt-3 inline-flex"
                  >
                    <Button variant="outline" size="sm" className="gap-1.5 rounded-full border-emerald-300 text-emerald-700 hover:bg-emerald-600 hover:text-white">
                      <MessageCircle className="size-4" /> Hubungi via WhatsApp
                    </Button>
                  </a>
                </section>

                <section className="rounded-2xl border p-4">
                  <h4 className="mb-3 text-sm font-bold uppercase tracking-wide text-[#8a6a10]">Berkas Unggahan</h4>
                  <div className="grid grid-cols-3 gap-3">
                    {[
                      { label: "Kartu Keluarga", path: detail.berkasKK },
                      { label: "Akta Kelahiran", path: detail.berkasAkta },
                      { label: "Ijazah/SKL", path: detail.berkasIjazah },
                    ].map((b) => {
                      const isImg = /\.(png|jpe?g)$/i.test(b.path);
                      return (
                        <a
                          key={b.label}
                          href={`/api/files/${b.path}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="group flex flex-col items-center gap-2 rounded-xl border-2 border-dashed p-3 text-center transition-colors hover:border-[#D4A017] hover:bg-[#D4A017]/5"
                        >
                          {isImg ? (
                            <img
                              src={`/api/files/${b.path}`}
                              alt={b.label}
                              className="h-16 w-full rounded-lg object-cover"
                            />
                          ) : (
                            <span className="grid h-16 w-full place-items-center rounded-lg bg-[#7B1E28]/10 text-[#7B1E28]">
                              <FileText className="size-7" />
                            </span>
                          )}
                          <span className="text-xs font-medium text-muted-foreground group-hover:text-[#7B1E28]">
                            {b.label} <ImageIcon className="inline size-3" />
                          </span>
                        </a>
                      );
                    })}
                  </div>
                </section>

                <section className="rounded-2xl border p-4">
                  <h4 className="mb-3 text-sm font-bold uppercase tracking-wide text-[#8a6a10]">Verifikasi Panitia</h4>
                  <RadioGroup value={patchStatus} onValueChange={setPatchStatus} className="grid grid-cols-2 gap-2">
                    {STATUS_LIST.map((s) => (
                      <Label
                        key={s}
                        htmlFor={`st-${s}`}
                        className={`flex cursor-pointer items-center gap-2 rounded-xl border-2 px-3 py-2.5 text-sm font-semibold transition-all ${
                          patchStatus === s ? "border-[#7B1E28] bg-[#7B1E28]/5 text-[#7B1E28]" : "text-muted-foreground hover:border-[#D4A017]"
                        }`}
                      >
                        <RadioGroupItem value={s} id={`st-${s}`} />
                        {STATUS_LABEL[s]}
                      </Label>
                    ))}
                  </RadioGroup>
                  <div className="mt-3">
                    <Label htmlFor="catatan" className="text-sm font-semibold text-[#4a1520]">
                      Catatan Verifikator
                    </Label>
                    <Textarea
                      id="catatan"
                      value={patchCatatan}
                      onChange={(e) => setPatchCatatan(e.target.value)}
                      placeholder="cth: Berkas lengkap dan valid; atau instruksi perbaikan untuk pendaftar"
                      className="mt-1.5 min-h-24 rounded-xl"
                    />
                  </div>
                  <Button
                    onClick={saveDetail}
                    disabled={saving}
                    className="mt-4 w-full gap-2 rounded-xl bg-gradient-to-r from-[#7B1E28] to-[#a32838] text-white h-11"
                  >
                    {saving ? <Loader2 className="size-4 animate-spin" /> : null}
                    {saving ? "Menyimpan…" : "Simpan Hasil Verifikasi"}
                  </Button>
                </section>
              </div>
            </>
          )}
        </SheetContent>
      </Sheet>
    </motion.div>
  );
}

function STATUS_LABEL_COLOR(status: string): string {
  switch (status) {
    case "DITERIMA":
      return "bg-emerald-100 text-emerald-800 border-emerald-300";
    case "CADANGAN":
      return "bg-sky-100 text-sky-800 border-sky-300";
    case "DITOLAK":
      return "bg-red-100 text-red-800 border-red-300";
    default:
      return "bg-amber-100 text-amber-800 border-amber-300";
  }
}
