import { createFileRoute, Link } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { useRef, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { ActionScreen } from "@/components/bkash/ActionScreen";
import { getMyKyc, submitKyc } from "@/lib/kyc.functions";
import { Camera, CheckCircle2, Clock, XCircle, Loader2, Upload, Shield } from "lucide-react";
import { toast } from "sonner";

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

type Slot = "front" | "back" | "selfie";
const LABELS: Record<Slot, { title: string; hint: string }> = {
  front: { title: "NID এর সামনের অংশ", hint: "স্পষ্ট, পুরো কার্ড ফ্রেমে থাকতে হবে" },
  back: { title: "NID এর পেছনের অংশ", hint: "ঠিকানা পড়া যায় এমন ছবি" },
  selfie: { title: "নিজের সেলফি", hint: "মুখ পরিষ্কারভাবে দেখা যাবে" },
};

async function sha256(file: File): Promise<string> {
  const buf = await file.arrayBuffer();
  const hash = await crypto.subtle.digest("SHA-256", buf);
  return Array.from(new Uint8Array(hash)).map((b) => b.toString(16).padStart(2, "0")).join("");
}

function KycPage() {
  const getKyc = useServerFn(getMyKyc);
  const submit = useServerFn(submitKyc);
  const qc = useQueryClient();
  const kycQ = useQuery({ queryKey: ["my-kyc"], queryFn: () => getKyc() });

  const [files, setFiles] = useState<Record<Slot, File | null>>({ front: null, back: null, selfie: null });
  const [previews, setPreviews] = useState<Record<Slot, string | null>>({ front: null, back: null, selfie: null });
  const inputs = { front: useRef<HTMLInputElement>(null), back: useRef<HTMLInputElement>(null), selfie: useRef<HTMLInputElement>(null) };

  const status = kycQ.data?.kyc_status ?? "unverified";
  const latest = kycQ.data?.latest;

  const mut = useMutation({
    mutationFn: async () => {
      if (!files.front || !files.back || !files.selfie) throw new Error("সব ছবি আপলোড করুন");
      const { data: userRes } = await supabase.auth.getUser();
      const uid = userRes.user?.id;
      if (!uid) throw new Error("লগইন করুন");

      const uploadOne = async (kind: Slot, file: File) => {
        const ext = (file.name.split(".").pop() || "jpg").toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 5);
        const path = `${uid}/${Date.now()}-${kind}.${ext || "jpg"}`;
        const { error } = await supabase.storage.from("kyc-documents").upload(path, file, {
          contentType: file.type || "image/jpeg",
          upsert: false,
        });
        if (error) throw new Error(`${kind} আপলোড ব্যর্থ: ${error.message}`);
        return path;
      };

      const [frontPath, backPath, selfiePath] = await Promise.all([
        uploadOne("front", files.front!),
        uploadOne("back", files.back!),
        uploadOne("selfie", files.selfie!),
      ]);
      const [frontHash, backHash, selfieHash] = await Promise.all([
        sha256(files.front!),
        sha256(files.back!),
        sha256(files.selfie!),
      ]);

      return await submit({ data: { frontPath, backPath, selfiePath, frontHash, backHash, selfieHash } });
    },
    onSuccess: (res) => {
      qc.invalidateQueries({ queryKey: ["my-kyc"] });
      qc.invalidateQueries({ queryKey: ["profile"] });
      if (res.status === "verified") toast.success("অভিনন্দন! NID ভেরিফাইড ✅");
      else toast.info("জমা হয়েছে — অ্যাডমিন রিভিউর অপেক্ষায় ⏳");
      setFiles({ front: null, back: null, selfie: null });
      setPreviews({ front: null, back: null, selfie: null });
    },
    onError: (e: any) => toast.error(e?.message ?? "সাবমিট ব্যর্থ"),
  });

  function pick(slot: Slot, file: File | null) {
    if (!file) return;
    if (file.size > 8 * 1024 * 1024) return toast.error("ছবি ৮MB এর কম হতে হবে");
    setFiles((p) => ({ ...p, [slot]: file }));
    setPreviews((p) => ({ ...p, [slot]: URL.createObjectURL(file) }));
  }

  const canResubmit = status === "unverified" || status === "rejected";
  const showForm = canResubmit;

  return (
    <ActionScreen title="NID ভেরিফিকেশন" subtitle="নিরাপদ লেনদেনের জন্য পরিচয় যাচাই">
      {/* Status */}
      <StatusCard status={status} latest={latest} />

      {showForm && (
        <>
          <div className="mt-4 space-y-3">
            {(Object.keys(LABELS) as Slot[]).map((slot) => (
              <div key={slot} className="bg-card rounded-2xl shadow-[var(--shadow-card)] p-3">
                <div className="flex items-start justify-between mb-2">
                  <div>
                    <p className="font-semibold text-sm">{LABELS[slot].title}</p>
                    <p className="text-[11px] text-muted-foreground">{LABELS[slot].hint}</p>
                  </div>
                  {files[slot] && <CheckCircle2 className="h-4 w-4 text-success" />}
                </div>

                {previews[slot] ? (
                  <div className="relative rounded-xl overflow-hidden aspect-[16/10] bg-muted">
                    <img src={previews[slot]!} alt={slot} className="w-full h-full object-cover" />
                    <button
                      onClick={() => inputs[slot].current?.click()}
                      className="absolute bottom-2 right-2 bg-black/60 text-white text-xs px-2.5 h-7 rounded-full font-semibold"
                    >
                      পরিবর্তন
                    </button>
                  </div>
                ) : (
                  <button
                    onClick={() => inputs[slot].current?.click()}
                    className="w-full aspect-[16/10] rounded-xl border-2 border-dashed border-border grid place-items-center text-muted-foreground hover:border-primary hover:text-primary transition"
                  >
                    <div className="text-center">
                      {slot === "selfie" ? <Camera className="h-6 w-6 mx-auto" /> : <Upload className="h-6 w-6 mx-auto" />}
                      <p className="text-xs mt-1.5 font-semibold">
                        {slot === "selfie" ? "সেলফি তুলুন" : "ছবি নির্বাচন"}
                      </p>
                    </div>
                  </button>
                )}

                <input
                  ref={inputs[slot]}
                  type="file"
                  accept="image/*"
                  capture={slot === "selfie" ? "user" : "environment"}
                  className="hidden"
                  onChange={(e) => pick(slot, e.target.files?.[0] ?? null)}
                />
              </div>
            ))}
          </div>

          <button
            onClick={() => mut.mutate()}
            disabled={mut.isPending || !files.front || !files.back || !files.selfie}
            className="mt-5 w-full h-12 rounded-full bg-primary text-primary-foreground font-bold text-sm disabled:opacity-50 flex items-center justify-center gap-2"
          >
            {mut.isPending ? (
              <><Loader2 className="h-4 w-4 animate-spin" /> AI চেক ও জমা দিচ্ছি…</>
            ) : (
              <>জমা দিন</>
            )}
          </button>

          <div className="mt-4 bg-muted/50 rounded-xl p-3 text-[11px] text-muted-foreground leading-relaxed">
            <p className="font-semibold text-foreground mb-1">🔒 গোপনীয়তা</p>
            আপনার ছবি শুধুমাত্র ভেরিফিকেশনের জন্য ব্যবহৃত হবে ও নিরাপদে সংরক্ষিত থাকবে। একই NID দিয়ে একাধিক অ্যাকাউন্ট করা যাবে না।
          </div>
        </>
      )}

      {!showForm && status !== "verified" && (
        <Link
          to="/"
          className="mt-4 block text-center h-12 rounded-full bg-muted text-foreground/70 font-semibold text-sm leading-[3rem]"
        >
          হোমে ফিরুন
        </Link>
      )}
      <div className="h-8" />
    </ActionScreen>
  );
}

function StatusCard({ status, latest }: { status: string; latest: any }) {
  const map: Record<string, { icon: any; color: string; title: string; body: string }> = {
    verified: { icon: CheckCircle2, color: "text-success", title: "ভেরিফাইড", body: "আপনি সব লেনদেন করতে পারবেন।" },
    pending: { icon: Clock, color: "text-primary", title: "প্রসেসিং", body: "AI চেক চলছে…" },
    needs_review: { icon: Clock, color: "text-primary", title: "অ্যাডমিন রিভিউ", body: "অ্যাডমিন রিভিউর অপেক্ষায় — সাধারণত ২৪ ঘন্টার মধ্যে হয়।" },
    rejected: { icon: XCircle, color: "text-destructive", title: "রিজেক্ট হয়েছে", body: latest?.review_note ?? "আবার আপলোড করুন।" },
    unverified: { icon: Shield, color: "text-primary", title: "অসম্পূর্ণ", body: "লেনদেন করতে হলে NID ভেরিফাই করুন।" },
  };
  const s = map[status] ?? map.unverified;
  const Icon = s.icon;
  return (
    <div className="bg-card rounded-2xl shadow-[var(--shadow-card)] p-4 flex items-start gap-3">
      <div className={`h-10 w-10 rounded-full bg-muted grid place-items-center shrink-0 ${s.color}`}>
        <Icon className="h-5 w-5" />
      </div>
      <div className="min-w-0">
        <p className="font-bold text-sm">{s.title}</p>
        <p className="text-xs text-muted-foreground mt-0.5">{s.body}</p>
        {latest?.ai_confidence != null && status !== "unverified" && (
          <p className="text-[10px] text-muted-foreground mt-1">AI স্কোর: {(latest.ai_confidence * 100).toFixed(0)}%</p>
        )}
      </div>
    </div>
  );
}
