import { createFileRoute } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { adminListReferralMappings, adminSetReferralMapping, adminVerifyReferralAutobinding } from "@/lib/customer-portal.functions";
import { PageLayout } from "@/components/PageLayout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { toast } from "sonner";
import { Search, Link2, Link2Off, Pencil, AlertTriangle, Users, ShieldCheck, CheckCircle2, XCircle, Clock, Phone } from "lucide-react";

export const Route = createFileRoute("/_authenticated/referral-mappings")({
  head: () => ({ meta: [{ title: "Referral Mappings — Niyamah ERP" }] }),
  component: ReferralMappingsPage,
});

type FilterKey = "all" | "linked" | "unlinked" | "orphan";

function fmt(iso: string | null | undefined) {
  if (!iso) return "—";
  try {
    return new Date(iso).toLocaleString("en-GB", { day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" });
  } catch { return "—"; }
}

function ReferralMappingsPage() {
  const qc = useQueryClient();
  const listFn = useServerFn(adminListReferralMappings);
  const setFn = useServerFn(adminSetReferralMapping);
  const verifyFn = useServerFn(adminVerifyReferralAutobinding);
  const [search, setSearch] = useState("");
  const [filter, setFilter] = useState<FilterKey>("all");
  const [editTarget, setEditTarget] = useState<{ id: string; name: string; current: string } | null>(null);
  const [editMobile, setEditMobile] = useState("");
  const [verifyResult, setVerifyResult] = useState<any>(null);

  const { data, isLoading } = useQuery({
    queryKey: ["referral-mappings", search, filter],
    queryFn: () => listFn({ data: { search, filter, limit: 500 } }),
  });

  const saveMut = useMutation({
    mutationFn: async (payload: { customer_id: string; reference_mobile: string }) => setFn({ data: payload }),
    onSuccess: () => {
      toast.success("রেফারেল আপডেট হয়েছে");
      setEditTarget(null);
      qc.invalidateQueries({ queryKey: ["referral-mappings"] });
    },
    onError: (e: any) => toast.error(e?.message || "ব্যর্থ"),
  });

  const verifyMut = useMutation({
    mutationFn: async () => verifyFn({}),
    onSuccess: (res: any) => {
      setVerifyResult(res);
      if (res?.ok) toast.success("অটো-বাইন্ডিং সঠিকভাবে কাজ করছে ✓");
      else toast.error("ভেরিফিকেশন ফেইল হয়েছে — ডিটেইল দেখুন");
    },
    onError: (e: any) => toast.error(e?.message || "ভেরিফিকেশন চালানো যায়নি"),
  });



  const rows = data?.rows || [];
  const pendingRows = data?.pendingRows || [];
  const stats = data?.stats || { total: 0, linked: 0, orphan: 0, none: 0, pending: 0 };

  return (
    <PageLayout title="Referral Mappings" subtitle="কাস্টমার রেফারেল সম্পর্ক ম্যানেজমেন্ট">
      <div className="space-y-4">
        <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
          <StatCard icon={Users} label="মোট" value={stats.total} tone="default" />
          <StatCard icon={Link2} label="লিঙ্কড" value={stats.linked} tone="success" />
          <StatCard icon={Clock} label="অপেক্ষমান" value={stats.pending} tone="warn" />
          <StatCard icon={AlertTriangle} label="অর্ফান" value={stats.orphan} tone="warn" />
          <StatCard icon={Link2Off} label="রেফারেল নেই" value={stats.none} tone="muted" />
        </div>

        <div className="rounded-2xl border bg-card p-4 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
          <div className="flex items-start gap-3">
            <div className="h-10 w-10 rounded-xl bg-primary/10 text-primary grid place-items-center shrink-0">
              <ShieldCheck className="h-5 w-5" />
            </div>
            <div>
              <div className="font-medium text-sm">অটো-বাইন্ডিং ভেরিফিকেশন</div>
              <div className="text-xs text-muted-foreground">টেস্ট কাস্টমার বানিয়ে instant referral linking যাচাই করে (সব rollback হয়)।</div>
            </div>
          </div>
          <Button onClick={() => verifyMut.mutate()} disabled={verifyMut.isPending} variant="outline">
            {verifyMut.isPending ? "চলছে..." : "Run Verification"}
          </Button>
        </div>

        {verifyResult && (
          <div className={`rounded-2xl border p-4 space-y-2 ${verifyResult.ok ? "bg-green-500/5 border-green-500/30" : "bg-destructive/5 border-destructive/30"}`}>
            <div className="flex items-center gap-2 font-medium">
              {verifyResult.ok ? <CheckCircle2 className="h-4 w-4 text-green-600" /> : <XCircle className="h-4 w-4 text-destructive" />}
              {verifyResult.ok ? "সব টেস্ট পাস হয়েছে" : "ভেরিফিকেশন ফেইল"}
            </div>
            {[verifyResult.test1_auto_link_on_register, verifyResult.test2_sync_on_reference_set].filter(Boolean).map((t: any, i: number) => (
              <div key={i} className="text-xs flex items-start gap-2 pl-1">
                {t.passed ? <CheckCircle2 className="h-3.5 w-3.5 text-green-600 mt-0.5 shrink-0" /> : <XCircle className="h-3.5 w-3.5 text-destructive mt-0.5 shrink-0" />}
                <span className="text-muted-foreground">{t.description}</span>
              </div>
            ))}
            {verifyResult.error && <div className="text-xs text-destructive">Error: {verifyResult.error}</div>}
          </div>
        )}


        <div className="flex flex-col sm:flex-row gap-3 sm:items-center sm:justify-between">
          <div className="relative max-w-sm w-full">
            <Search className="h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="নাম / মোবাইল / রেফারেল মোবাইল"
              className="pl-9"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
          </div>
          <Tabs value={filter} onValueChange={(v) => setFilter(v as FilterKey)}>
            <TabsList>
              <TabsTrigger value="all">সব</TabsTrigger>
              <TabsTrigger value="linked">লিঙ্কড</TabsTrigger>
              <TabsTrigger value="unlinked">আনলিঙ্কড</TabsTrigger>
              <TabsTrigger value="orphan">অর্ফান</TabsTrigger>
            </TabsList>
          </Tabs>
        </div>

        <div className="rounded-2xl border bg-card p-4 space-y-3">
          <div className="flex items-center justify-between gap-3">
            <div>
              <h3 className="font-medium flex items-center gap-2"><Clock className="h-4 w-4 text-primary" />অপেক্ষমান রেফারেন্স</h3>
              <p className="text-xs text-muted-foreground">যেসব নাম্বার এখনো কাস্টমার হিসেবে রেজিস্টার হয়নি</p>
            </div>
            <Badge variant="outline">{pendingRows.length} টি</Badge>
          </div>

          {pendingRows.length === 0 ? (
            <div className="rounded-xl border border-dashed py-8 text-center text-sm text-muted-foreground">কোনো অপেক্ষমান রেফারেন্স নেই</div>
          ) : (
            <div className="space-y-2">
              {pendingRows.map((r: any) => (
                <div key={r.id} className="rounded-xl border px-4 py-3 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                  <div className="space-y-1 min-w-0">
                    <div className="flex items-center gap-2 text-sm font-medium">
                      <Phone className="h-3.5 w-3.5 text-muted-foreground" />
                      <span className="font-mono">{r.mobile}</span>
                    </div>
                    <div className="text-xs text-muted-foreground">
                      রেফারার: {r.referrer ? (r.referrer.name_bn || r.referrer.name) : "—"}
                      {r.referrer?.mobile ? <span className="font-mono"> ({r.referrer.mobile})</span> : null}
                    </div>
                    {r.note ? <div className="text-xs text-muted-foreground">নোট: {r.note}</div> : null}
                  </div>
                  <div className="flex items-center gap-3 shrink-0">
                    <Badge className="bg-amber-500/10 text-amber-700 hover:bg-amber-500/10 border-amber-500/20">Pending</Badge>
                    <div className="text-xs text-muted-foreground">{fmt(r.created_at)}</div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="rounded-2xl border bg-card overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>কাস্টমার</TableHead>
                <TableHead>মোবাইল</TableHead>
                <TableHead>রেফারার</TableHead>
                <TableHead>রেফারেল মোবাইল</TableHead>
                <TableHead>স্ট্যাটাস</TableHead>
                <TableHead>আপডেটেড</TableHead>
                <TableHead className="text-right">অ্যাকশন</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableRow><TableCell colSpan={7} className="text-center py-8 text-muted-foreground">লোড হচ্ছে...</TableCell></TableRow>
              ) : rows.length === 0 ? (
                <TableRow><TableCell colSpan={7} className="text-center py-8 text-muted-foreground">কোনো ডেটা নেই</TableCell></TableRow>
              ) : rows.map((r) => {
                const linked = !!r.reference_customer_id;
                const orphan = !linked && !!r.reference_mobile;
                return (
                  <TableRow key={r.id}>
                    <TableCell>
                      <div className="font-medium">{r.name_bn || r.name}</div>
                      {r.name_bn && r.name && <div className="text-xs text-muted-foreground">{r.name}</div>}
                    </TableCell>
                    <TableCell className="font-mono text-xs">{r.mobile}</TableCell>
                    <TableCell>
                      {r.referrer ? (
                        <div>
                          <div className="text-sm">{r.referrer.name_bn || r.referrer.name}</div>
                          <div className="text-xs font-mono text-muted-foreground">{r.referrer.mobile}</div>
                        </div>
                      ) : <span className="text-muted-foreground">—</span>}
                    </TableCell>
                    <TableCell className="font-mono text-xs">{r.reference_mobile || "—"}</TableCell>
                    <TableCell>
                      {linked ? <Badge variant="default" className="bg-green-600"><Link2 className="h-3 w-3 mr-1" />Linked</Badge>
                        : orphan ? <Badge variant="destructive"><AlertTriangle className="h-3 w-3 mr-1" />Orphan</Badge>
                        : <Badge variant="outline"><Link2Off className="h-3 w-3 mr-1" />None</Badge>}
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground">{fmt(r.updated_at)}</TableCell>
                    <TableCell className="text-right">
                      <Button size="sm" variant="outline" onClick={() => {
                        setEditTarget({ id: r.id, name: r.name_bn || r.name, current: r.reference_mobile });
                        setEditMobile(r.reference_mobile);
                      }}>
                        <Pencil className="h-3.5 w-3.5 mr-1" />Edit
                      </Button>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </div>
      </div>

      <Dialog open={!!editTarget} onOpenChange={(o) => !o && setEditTarget(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>রেফারেল ম্যাপিং পরিবর্তন</DialogTitle>
          </DialogHeader>
          <div className="space-y-3">
            <div className="text-sm">কাস্টমার: <span className="font-medium">{editTarget?.name}</span></div>
            <div>
              <Label>রেফারেল মোবাইল</Label>
              <Input
                value={editMobile}
                onChange={(e) => setEditMobile(e.target.value)}
                placeholder="01XXXXXXXXX (খালি রাখলে রিমুভ হবে)"
              />
              <p className="text-[10px] text-muted-foreground mt-1">খালি রাখলে রেফারেল সম্পর্ক মুছে যাবে। নতুন নাম্বার দিলে অবশ্যই রেজিস্টার্ড কাস্টমার হতে হবে।</p>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditTarget(null)}>বাতিল</Button>
            <Button
              disabled={saveMut.isPending}
              onClick={() => editTarget && saveMut.mutate({ customer_id: editTarget.id, reference_mobile: editMobile })}
            >
              {saveMut.isPending ? "সেভ হচ্ছে..." : "সেভ করুন"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </PageLayout>
  );
}

function StatCard({ icon: Icon, label, value, tone }: { icon: any; label: string; value: number; tone: "default" | "success" | "warn" | "muted" }) {
  const colorMap: Record<string, string> = {
    default: "text-primary bg-primary/10",
    success: "text-green-600 bg-green-600/10",
    warn: "text-amber-600 bg-amber-600/10",
    muted: "text-muted-foreground bg-muted",
  };
  return (
    <div className="rounded-2xl border bg-card p-4 flex items-center gap-3">
      <div className={`h-10 w-10 rounded-xl grid place-items-center ${colorMap[tone]}`}><Icon className="h-5 w-5" /></div>
      <div>
        <div className="text-2xl font-bold">{value}</div>
        <div className="text-xs text-muted-foreground">{label}</div>
      </div>
    </div>
  );
}
