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 { getMyProfileDetails, setMyAvatar, setMyName } from "@/lib/bkash.functions";
import { Camera, Loader2, CheckCircle2, Clock, XCircle, Shield, IdCard, Pencil, Check, X } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/profile-info")({
  component: ProfileInfoPage,
});

const STATUS: Record<string, { label: string; color: string; Icon: any }> = {
  verified: { label: "ভেরিফাইড", color: "text-success", Icon: CheckCircle2 },
  needs_review: { label: "রিভিউতে", color: "text-primary", Icon: Clock },
  pending: { label: "প্রসেসিং", color: "text-primary", Icon: Clock },
  rejected: { label: "রিজেক্ট", color: "text-destructive", Icon: XCircle },
  unverified: { label: "অসম্পূর্ণ", color: "text-muted-foreground", Icon: Shield },
};

function ProfileInfoPage() {
  const getDetails = useServerFn(getMyProfileDetails);
  const saveAvatar = useServerFn(setMyAvatar);
  const saveName = useServerFn(setMyName);
  const qc = useQueryClient();
  const q = useQuery({ queryKey: ["profile-details"], queryFn: () => getDetails() });
  const fileRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);
  const [editingName, setEditingName] = useState(false);
  const [nameDraft, setNameDraft] = useState("");
  const [savingName, setSavingName] = useState(false);

  const profile = q.data?.profile;
  const kyc = q.data?.kyc;
  const status = profile?.kyc_status ?? "unverified";
  const S = STATUS[status] ?? STATUS.unverified;

  const avatarSrc = profile?.avatar_url ?? kyc?.selfie_url ?? null;

  const mut = useMutation({
    mutationFn: async (file: File) => {
      const { data: userRes } = await supabase.auth.getUser();
      const uid = userRes.user?.id;
      if (!uid) throw new Error("লগইন করুন");
      const ext = (file.name.split(".").pop() || "jpg").toLowerCase().replace(/[^a-z0-9]/g, "").slice(0, 5);
      const path = `${uid}/avatar-${Date.now()}.${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(error.message);
      return await saveAvatar({ data: { avatarPath: path } });
    },
    onMutate: () => setUploading(true),
    onSettled: () => setUploading(false),
    onSuccess: async () => {
      await Promise.all([
        qc.refetchQueries({ queryKey: ["profile-details"], type: "all" }),
        qc.refetchQueries({ queryKey: ["profile"], type: "all" }),
      ]);
      toast.success("ছবি আপডেট হয়েছে");
    },
    onError: (e: any) => toast.error(e?.message ?? "আপলোড ব্যর্থ"),
  });

  function pick(file: File | null) {
    if (!file) return;
    if (file.size > 5 * 1024 * 1024) return toast.error("ছবি ৫MB এর কম হতে হবে");
    mut.mutate(file);
  }

  async function submitName() {
    const v = nameDraft.trim();
    if (v.length < 2) return toast.error("নাম কমপক্ষে ২ অক্ষরের হতে হবে");
    setSavingName(true);
    try {
      await saveName({ data: { fullName: v } });
      toast.success("নাম আপডেট হয়েছে");
      setEditingName(false);
      await Promise.all([
        qc.refetchQueries({ queryKey: ["profile-details"], type: "all" }),
        qc.refetchQueries({ queryKey: ["profile"], type: "all" }),
      ]);
    } catch (e: any) {
      toast.error(e?.message ?? "সংরক্ষণ ব্যর্থ");
    } finally {
      setSavingName(false);
    }
  }


  return (
    <ActionScreen title="প্রোফাইল তথ্য" subtitle="আপনার ব্যক্তিগত ও KYC তথ্য">
      {/* Header card with avatar top-right */}
      <div className="bg-card rounded-2xl shadow-[var(--shadow-elevated)] p-5 relative">
        <div className="absolute top-4 right-4">
          <button
            onClick={() => fileRef.current?.click()}
            className="relative h-20 w-20 rounded-full overflow-hidden ring-2 ring-primary/30 bg-muted grid place-items-center"
          >
            {avatarSrc ? (
              <img src={avatarSrc} alt="avatar" className="h-full w-full object-cover" />
            ) : (
              <span className="text-2xl font-bold text-muted-foreground">
                {(profile?.full_name ?? "?").charAt(0).toUpperCase()}
              </span>
            )}
            <span className="absolute bottom-0 inset-x-0 bg-black/55 text-white text-[10px] py-0.5 flex items-center justify-center gap-1">
              {uploading ? <Loader2 className="h-3 w-3 animate-spin" /> : <Camera className="h-3 w-3" />}
              {uploading ? "" : "পরিবর্তন"}
            </span>
          </button>
          <input
            ref={fileRef}
            type="file"
            accept="image/*"
            className="hidden"
            onChange={(e) => pick(e.target.files?.[0] ?? null)}
          />
        </div>

        <div className="pr-24">
          <p className="text-xs text-muted-foreground">নাম</p>
          {editingName ? (
            <div className="flex items-center gap-1.5 mt-1">
              <input
                autoFocus
                value={nameDraft}
                onChange={(e) => setNameDraft(e.target.value)}
                maxLength={60}
                className="flex-1 min-w-0 h-9 px-2 rounded-lg border border-input bg-background text-sm font-semibold outline-none focus:border-primary"
                placeholder="আপনার নাম"
              />
              <button
                onClick={submitName}
                disabled={savingName}
                className="h-9 w-9 rounded-lg bg-primary text-primary-foreground grid place-items-center disabled:opacity-50"
                aria-label="সেভ"
              >
                {savingName ? <Loader2 className="h-4 w-4 animate-spin" /> : <Check className="h-4 w-4" />}
              </button>
              <button
                onClick={() => setEditingName(false)}
                disabled={savingName}
                className="h-9 w-9 rounded-lg bg-muted grid place-items-center"
                aria-label="বাতিল"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
          ) : (
            <div className="flex items-center gap-2">
              <p className="font-bold text-lg leading-tight">{profile?.full_name ?? "..."}</p>
              <button
                onClick={() => {
                  setNameDraft(profile?.full_name ?? "");
                  setEditingName(true);
                }}
                className="h-6 w-6 rounded-md grid place-items-center text-primary hover:bg-primary/10"
                aria-label="নাম পরিবর্তন"
              >
                <Pencil className="h-3.5 w-3.5" />
              </button>
            </div>
          )}
          <p className="text-xs text-muted-foreground mt-2">মোবাইল নম্বর</p>
          <p className="font-semibold tabular-nums">{profile?.phone ?? "..."}</p>
          <div className={`mt-3 inline-flex items-center gap-1.5 text-xs font-semibold ${S.color}`}>
            <S.Icon className="h-3.5 w-3.5" />
            {S.label}
          </div>
        </div>
      </div>

      {/* KYC info */}
      <div className="mt-4 bg-card rounded-2xl shadow-[var(--shadow-card)] overflow-hidden">
        <div className="px-5 pt-4 pb-2 flex items-center gap-2">
          <IdCard className="h-4 w-4 text-primary" />
          <p className="font-bold text-sm">KYC তথ্য</p>
        </div>
        {kyc ? (
          <div className="divide-y divide-border">
            <Field label="NID নম্বর" value={kyc.nid_number} mono />
            <Field label="NID অনুযায়ী নাম" value={kyc.name_on_nid} />
            <Field label="জন্ম তারিখ" value={kyc.dob} />
            <Field label="ঠিকানা" value={kyc.address} />
            <Field label="স্ট্যাটাস" value={STATUS[kyc.status ?? "unverified"]?.label ?? kyc.status} />
            {kyc.ai_confidence != null && (
              <Field label="AI স্কোর" value={`${(Number(kyc.ai_confidence) * 100).toFixed(0)}%`} />
            )}
            {kyc.review_note && <Field label="রিভিউ নোট" value={kyc.review_note} />}
            <Field label="জমা দেওয়া" value={new Date(kyc.created_at).toLocaleString("bn-BD")} />
          </div>
        ) : (
          <div className="p-5 text-center">
            <p className="text-sm text-muted-foreground">এখনো KYC জমা দেননি।</p>
            <Link to="/kyc" className="mt-3 inline-block h-10 px-5 rounded-full bg-primary text-primary-foreground font-semibold text-sm leading-[2.5rem]">
              এখনই ভেরিফাই করুন
            </Link>
          </div>
        )}
      </div>

      {/* KYC images */}
      {kyc && (
        <div className="mt-4 bg-card rounded-2xl shadow-[var(--shadow-card)] p-4">
          <p className="font-bold text-sm mb-3">জমাকৃত ছবি</p>
          <div className="grid grid-cols-3 gap-2">
            <ImageTile label="NID ফ্রন্ট" src={kyc.front_url} />
            <ImageTile label="NID ব্যাক" src={kyc.back_url} />
            <ImageTile label="সেলফি" src={kyc.selfie_url} />
          </div>
          {(status === "rejected" || status === "unverified") && (
            <Link to="/kyc" className="mt-3 block text-center h-10 rounded-full bg-muted text-foreground font-semibold text-sm leading-[2.5rem]">
              আবার জমা দিন
            </Link>
          )}
        </div>
      )}

      <div className="h-8" />
    </ActionScreen>
  );
}

function Field({ label, value, mono }: { label: string; value?: string | null; mono?: boolean }) {
  return (
    <div className="flex items-start justify-between gap-3 px-5 py-3">
      <span className="text-xs text-muted-foreground shrink-0">{label}</span>
      <span className={`text-sm font-semibold text-right break-words ${mono ? "tabular-nums" : ""}`}>
        {value || "—"}
      </span>
    </div>
  );
}

function ImageTile({ label, src }: { label: string; src?: string | null }) {
  return (
    <div>
      <div className="aspect-square rounded-xl overflow-hidden bg-muted grid place-items-center">
        {src ? (
          <a href={src} target="_blank" rel="noreferrer" className="block w-full h-full">
            <img src={src} alt={label} className="w-full h-full object-cover" />
          </a>
        ) : (
          <span className="text-[10px] text-muted-foreground">নেই</span>
        )}
      </div>
      <p className="text-[10px] text-center mt-1 text-muted-foreground">{label}</p>
    </div>
  );
}
