import { createFileRoute } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { useState } from "react";
import { adminListKyc, adminReviewKyc } from "@/lib/kyc.functions";
import { CheckCircle2, XCircle, Loader2, Shield } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/admin/kyc")({
  component: AdminKycPage,
});

const FILTERS = [
  { key: "needs_review", label: "রিভিউতে" },
  { key: "verified", label: "ভেরিফাইড" },
  { key: "rejected", label: "রিজেক্ট" },
  { key: "all", label: "সব" },
] as const;

function AdminKycPage() {
  const list = useServerFn(adminListKyc);
  const review = useServerFn(adminReviewKyc);
  const qc = useQueryClient();
  const [filter, setFilter] = useState<(typeof FILTERS)[number]["key"]>("needs_review");
  const [notes, setNotes] = useState<Record<string, string>>({});

  const q = useQuery({
    queryKey: ["admin-kyc", filter],
    queryFn: () => list({ data: { filter } }),
  });

  const mut = useMutation({
    mutationFn: (v: { kycId: string; approve: boolean; note?: string }) => review({ data: v }),
    onSuccess: (_r, v) => {
      qc.invalidateQueries({ queryKey: ["admin-kyc"] });
      toast.success(v.approve ? "অ্যাপ্রুভ হয়েছে" : "রিজেক্ট করা হয়েছে");
    },
    onError: (e: any) => toast.error(e?.message ?? "ব্যর্থ"),
  });

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-xl font-bold flex items-center gap-2"><Shield className="h-5 w-5 text-primary" /> KYC রিভিউ</h1>
        <p className="text-sm text-muted-foreground">ইউজার NID ভেরিফিকেশন অনুমোদন / প্রত্যাখ্যান</p>
      </div>

      <div className="flex gap-2 overflow-x-auto pb-1">
        {FILTERS.map((f) => (
          <button key={f.key} onClick={() => setFilter(f.key)}
            className={`shrink-0 px-3 h-8 rounded-full text-xs font-semibold ${
              filter === f.key ? "bg-primary text-primary-foreground" : "bg-muted text-foreground/70"
            }`}>{f.label}</button>
        ))}
      </div>

      {q.isLoading && <div className="p-8 text-center"><Loader2 className="h-5 w-5 animate-spin mx-auto text-primary" /></div>}
      {!q.isLoading && (q.data?.length ?? 0) === 0 && (
        <div className="p-8 text-center text-sm text-muted-foreground bg-card rounded-2xl">কোনো রেকর্ড নেই</div>
      )}

      <div className="grid gap-4">
        {(q.data ?? []).map((r: any) => (
          <div key={r.id} className="bg-card rounded-2xl shadow-[var(--shadow-card)] p-4">
            <div className="flex items-start justify-between gap-2 flex-wrap">
              <div>
                <p className="font-bold text-sm">{r.profile?.full_name ?? "—"} <span className="text-muted-foreground font-normal">· {r.profile?.phone}</span></p>
                <p className="text-xs text-muted-foreground">
                  NID: <span className="tabular-nums">{r.nid_number ?? "N/A"}</span> · DOB: {r.dob ?? "N/A"}
                </p>
                <p className="text-[11px] text-muted-foreground mt-1">
                  {new Date(r.created_at).toLocaleString("en-GB")} · AI: {r.ai_confidence != null ? `${(r.ai_confidence * 100).toFixed(0)}%` : "—"}
                </p>
              </div>
              <span className={`text-[10px] font-bold px-2 h-6 rounded-full grid place-items-center ${
                r.status === "verified" ? "bg-success/10 text-success" :
                r.status === "rejected" ? "bg-destructive/10 text-destructive" :
                "bg-primary/10 text-primary"
              }`}>{r.status}</span>
            </div>

            {r.ai_notes && (
              <p className="mt-2 text-[11px] bg-muted/60 rounded-lg p-2 text-muted-foreground">AI: {r.ai_notes}</p>
            )}

            <div className="mt-3 grid grid-cols-3 gap-2">
              {[
                { url: r.front_url, label: "Front" },
                { url: r.back_url, label: "Back" },
                { url: r.selfie_url, label: "Selfie" },
              ].map((img) => (
                <a key={img.label} href={img.url} target="_blank" rel="noreferrer" className="block">
                  <div className="aspect-square rounded-lg overflow-hidden bg-muted">
                    {img.url ? <img src={img.url} alt={img.label} className="w-full h-full object-cover" /> : null}
                  </div>
                  <p className="text-[10px] text-center text-muted-foreground mt-1">{img.label}</p>
                </a>
              ))}
            </div>

            {r.status !== "verified" && r.status !== "rejected" && (
              <>
                <textarea
                  placeholder="নোট (ঐচ্ছিক)"
                  value={notes[r.id] ?? ""}
                  onChange={(e) => setNotes((p) => ({ ...p, [r.id]: e.target.value }))}
                  className="mt-3 w-full text-xs p-2 rounded-lg border bg-background"
                  rows={2}
                />
                <div className="mt-2 flex gap-2">
                  <button
                    disabled={mut.isPending}
                    onClick={() => mut.mutate({ kycId: r.id, approve: true, note: notes[r.id] })}
                    className="flex-1 h-10 rounded-lg bg-success text-white text-xs font-bold flex items-center justify-center gap-1 disabled:opacity-50"
                  >
                    <CheckCircle2 className="h-4 w-4" /> অ্যাপ্রুভ
                  </button>
                  <button
                    disabled={mut.isPending}
                    onClick={() => mut.mutate({ kycId: r.id, approve: false, note: notes[r.id] || "ছবি স্পষ্ট নয়" })}
                    className="flex-1 h-10 rounded-lg bg-destructive text-white text-xs font-bold flex items-center justify-center gap-1 disabled:opacity-50"
                  >
                    <XCircle className="h-4 w-4" /> রিজেক্ট
                  </button>
                </div>
              </>
            )}

            {r.review_note && (
              <p className="mt-2 text-[11px] text-muted-foreground">রিভিউ নোট: {r.review_note}</p>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
