import { createFileRoute } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { adminReferralLookup } from "@/lib/customer-portal.functions";
import { PageLayout } from "@/components/PageLayout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { toast } from "sonner";
import { Search, User, Link2, AlertTriangle, ArrowDown, ArrowUp, Users, Phone, Clock } from "lucide-react";

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

function fmt(iso?: string | null) {
  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 ReferralLookupPage() {
  const lookupFn = useServerFn(adminReferralLookup);
  const [mobile, setMobile] = useState("");
  const [result, setResult] = useState<any>(null);

  const lookupMut = useMutation({
    mutationFn: async (mob: string) => lookupFn({ data: { mobile: mob } }),
    onSuccess: (res) => setResult(res),
    onError: (e: any) => toast.error(e?.message || "Lookup failed"),
  });

  const onSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const m = mobile.trim();
    if (!m) return toast.error("মোবাইল নাম্বার দিন");
    lookupMut.mutate(m);
  };

  return (
    <PageLayout title="Referral Lookup" subtitle="মোবাইল নাম্বার দিয়ে রেফারেল চেইন যাচাই করুন">
      <div className="space-y-6 max-w-5xl">
        <form onSubmit={onSearch} className="rounded-2xl border bg-card p-4 flex flex-col sm:flex-row gap-3">
          <div className="relative flex-1">
            <Phone className="h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
            <Input
              autoFocus
              value={mobile}
              onChange={(e) => setMobile(e.target.value)}
              placeholder="01XXXXXXXXX"
              className="pl-9"
            />
          </div>
          <Button type="submit" disabled={lookupMut.isPending}>
            <Search className="h-4 w-4 mr-2" />
            {lookupMut.isPending ? "খোঁজা হচ্ছে..." : "খুঁজুন"}
          </Button>
        </form>

        {result && (
          <div className="space-y-5">
            {/* SELF */}
            <SectionCard
              icon={User}
              title="এই মোবাইলের কাস্টমার"
              empty={!result.self}
              emptyText="এই মোবাইলে এখনো কোনো কাস্টমার রেজিস্টার্ড নয় — তাই এটি orphan referral হিসেবে অপেক্ষায় থাকতে পারে।"
            >
              {result.self && (
                <div className="grid sm:grid-cols-2 gap-4">
                  <Field label="নাম" value={result.self.name_bn || result.self.name} />
                  <Field label="মোবাইল" value={result.self.mobile} mono />
                  <Field label="রেজিস্টার্ড" value={fmt(result.self.created_at)} icon={Clock} />
                  <Field label="নিজে রেফার করা হয়েছে?" value={result.self.reference_mobile || "না"} mono />
                </div>
              )}
            </SectionCard>

            {/* REFERRER (upline) */}
            <SectionCard
              icon={ArrowUp}
              title="যার রেফারেলে এসেছে (Referrer)"
              empty={!result.referrer}
              emptyText={result.self?.reference_mobile
                ? "রেফারেল মোবাইল সেট আছে কিন্তু এখনো ম্যাচ হয়নি — সেই মোবাইলে কোনো কাস্টমার রেজিস্টার করলে অটো লিঙ্ক হবে।"
                : "এই কাস্টমার কারো রেফারেলে আসেনি।"}
            >
              {result.referrer && (
                <div className="grid sm:grid-cols-2 gap-4">
                  <Field label="রেফারারের নাম" value={result.referrer.name_bn || result.referrer.name} />
                  <Field label="রেফারারের মোবাইল" value={result.referrer.mobile} mono />
                  <div className="sm:col-span-2">
                    <Badge variant="default" className="bg-green-600">
                      <Link2 className="h-3 w-3 mr-1" /> Auto-linked
                    </Badge>
                  </div>
                </div>
              )}
            </SectionCard>

            {/* DOWNLINE */}
            <SectionCard
              icon={ArrowDown}
              title="যাদেরকে এই মোবাইল রেফার করেছে (Downline)"
              empty={result.downline.length === 0}
              emptyText="এই মোবাইলকে কেউ রেফারেল হিসেবে ব্যবহার করেনি।"
            >
              {result.downline.length > 0 && (
                <>
                  <div className="flex flex-wrap gap-2 mb-3 text-xs">
                    <Badge variant="outline"><Users className="h-3 w-3 mr-1" />মোট {result.downline_stats.total}</Badge>
                    <Badge variant="default" className="bg-green-600"><Link2 className="h-3 w-3 mr-1" />Linked {result.downline_stats.linked}</Badge>
                    {result.downline_stats.orphan > 0 && (
                      <Badge variant="destructive"><AlertTriangle className="h-3 w-3 mr-1" />Orphan {result.downline_stats.orphan}</Badge>
                    )}
                  </div>
                  <div className="rounded-xl border overflow-x-auto">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>কাস্টমার</TableHead>
                          <TableHead>মোবাইল</TableHead>
                          <TableHead>স্ট্যাটাস</TableHead>
                          <TableHead>রেজিস্টার্ড</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {result.downline.map((r: any) => (
                          <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.reference_customer_id
                                ? <Badge variant="default" className="bg-green-600"><Link2 className="h-3 w-3 mr-1" />Linked</Badge>
                                : <Badge variant="destructive"><AlertTriangle className="h-3 w-3 mr-1" />Orphan</Badge>}
                            </TableCell>
                            <TableCell className="text-xs text-muted-foreground">{fmt(r.created_at)}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                </>
              )}
            </SectionCard>
          </div>
        )}
      </div>
    </PageLayout>
  );
}

function SectionCard({
  icon: Icon, title, children, empty, emptyText,
}: { icon: any; title: string; children: React.ReactNode; empty?: boolean; emptyText?: string }) {
  return (
    <div className="rounded-2xl border bg-card p-5">
      <div className="flex items-center gap-2 mb-4">
        <div className="h-8 w-8 rounded-lg bg-primary/10 text-primary grid place-items-center">
          <Icon className="h-4 w-4" />
        </div>
        <h3 className="font-semibold">{title}</h3>
      </div>
      {empty ? (
        <p className="text-sm text-muted-foreground">{emptyText}</p>
      ) : children}
    </div>
  );
}

function Field({ label, value, mono, icon: Icon }: { label: string; value: string; mono?: boolean; icon?: any }) {
  return (
    <div>
      <div className="text-xs text-muted-foreground mb-1 flex items-center gap-1">
        {Icon && <Icon className="h-3 w-3" />}
        {label}
      </div>
      <div className={`text-sm font-medium ${mono ? "font-mono" : ""}`}>{value}</div>
    </div>
  );
}
