import { createFileRoute, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { supabase } from "@/integrations/supabase/client";
import { useQuery } from "@tanstack/react-query";
import { useMemo, useState, useEffect } from "react";
import { Search, Crown, UserCheck, Sparkles, Moon, Settings as SettingsIcon, Download, Phone, History as HistoryIcon } from "lucide-react";
import {
  SegmentBadge,
  computeSegment,
  DEFAULT_THRESHOLDS,
  SEGMENT_META,
  type CustomerSegment,
  type SegmentThresholds,
} from "@/components/customers/SegmentBadge";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/customer-segments")({
  head: () => ({
    meta: [
      { title: "Customer Segmentation — Niyamah ERP" },
      { name: "description", content: "VIP, Regular, New ও Inactive customer auto segmentation" },
    ],
  }),
  component: CustomerSegmentsPage,
});

const STORAGE_KEY = "customer-segment-thresholds";

function loadThresholds(): SegmentThresholds {
  try {
    const raw = typeof window !== "undefined" ? localStorage.getItem(STORAGE_KEY) : null;
    if (raw) return { ...DEFAULT_THRESHOLDS, ...JSON.parse(raw) };
  } catch {}
  return DEFAULT_THRESHOLDS;
}

function CustomerSegmentsPage() {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const [thresholds, setThresholds] = useState<SegmentThresholds>(DEFAULT_THRESHOLDS);
  const [showSettings, setShowSettings] = useState(false);
  const [search, setSearch] = useState("");
  const [filter, setFilter] = useState<CustomerSegment | "all">("all");
  const [historyCustomer, setHistoryCustomer] = useState<any | null>(null);

  useEffect(() => {
    setThresholds(loadThresholds());
  }, []);

  const { data: customers = [], isLoading: cLoading } = useQuery({
    queryKey: ["seg-customers"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("customers" as any)
        .select("id, name, name_bn, mobile, created_at, current_balance, total_due, status")
        .is("deleted_at", null)
        .order("created_at", { ascending: false })
        .limit(2000);
      if (error) throw error;
      return (data as any[]) || [];
    },
  });

  const { data: sales = [], isLoading: sLoading } = useQuery({
    queryKey: ["seg-sales"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("sales" as any)
        .select("id, customer_id, customer_mobile, total_amount, sale_date, created_at")
        .order("sale_date", { ascending: false })
        .limit(5000);
      if (error) throw error;
      return (data as any[]) || [];
    },
  });

  const { data: wallets = [] } = useQuery({
    queryKey: ["seg-wallets"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("referral_wallets" as any)
        .select("customer_id, balance");
      if (error) throw error;
      return (data as any[]) || [];
    },
  });

  const walletMap = useMemo(() => {
    const m = new Map<string, number>();
    for (const w of wallets as any[]) m.set(w.customer_id, Number(w.balance) || 0);
    return m;
  }, [wallets]);

  // Aggregate sales by customer
  const salesAgg = useMemo(() => {
    const now = Date.now();
    const monthAgo = now - 30 * 86400000;
    const agg = new Map<
      string,
      { totalPurchase: number; totalOrders: number; monthlyOrders: number; lastPurchase: string | null }
    >();
    for (const s of sales as any[]) {
      const key = s.customer_id || s.customer_mobile;
      if (!key) continue;
      const cur =
        agg.get(key) || { totalPurchase: 0, totalOrders: 0, monthlyOrders: 0, lastPurchase: null };
      cur.totalPurchase += Number(s.total_amount) || 0;
      cur.totalOrders += 1;
      const t = new Date(s.sale_date || s.created_at).getTime();
      if (t >= monthAgo) cur.monthlyOrders += 1;
      if (!cur.lastPurchase || new Date(cur.lastPurchase).getTime() < t) {
        cur.lastPurchase = new Date(t).toISOString();
      }
      agg.set(key, cur);
    }
    return agg;
  }, [sales]);

  const rows = useMemo(() => {
    return (customers as any[]).map((c) => {
      const a = salesAgg.get(c.id) || salesAgg.get(c.mobile) || {
        totalPurchase: 0,
        totalOrders: 0,
        monthlyOrders: 0,
        lastPurchase: null as string | null,
      };
      const segment = computeSegment(
        {
          created_at: c.created_at,
          totalPurchase: a.totalPurchase,
          monthlyOrders: a.monthlyOrders,
          lastPurchaseDate: a.lastPurchase,
        },
        thresholds,
      );
      return {
        ...c,
        totalPurchase: a.totalPurchase,
        totalOrders: a.totalOrders,
        monthlyOrders: a.monthlyOrders,
        lastPurchase: a.lastPurchase,
        wallet: walletMap.get(c.id) || 0,
        segment,
      };
    });
  }, [customers, salesAgg, walletMap, thresholds]);

  const counts = useMemo(() => {
    const m: Record<CustomerSegment, number> = { vip: 0, regular: 0, new: 0, inactive: 0 };
    for (const r of rows) m[r.segment as CustomerSegment]++;
    return m;
  }, [rows]);

  // Fetch latest segment log per customer to detect changes
  const { data: latestLogs = [] } = useQuery({
    queryKey: ["seg-latest-logs"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("customer_segment_logs" as any)
        .select("customer_id, new_segment, created_at")
        .order("created_at", { ascending: false })
        .limit(5000);
      if (error) throw error;
      return (data as any[]) || [];
    },
  });

  const latestSegMap = useMemo(() => {
    const m = new Map<string, string>();
    for (const l of latestLogs as any[]) {
      if (!m.has(l.customer_id)) m.set(l.customer_id, l.new_segment);
    }
    return m;
  }, [latestLogs]);

  // Auto-log segment changes (only when rows + logs both loaded)
  useEffect(() => {
    if (!rows.length || (cLoading || sLoading)) return;
    const toInsert: Array<{ customer_id: string; old_segment: string | null; new_segment: string; reason: string }> = [];
    for (const r of rows) {
      const prev = latestSegMap.get(r.id);
      if (prev !== r.segment) {
        const lastTxt = r.lastPurchase
          ? `${Math.floor((Date.now() - new Date(r.lastPurchase).getTime()) / 86400000)}d ago`
          : "never";
        const reason = `auto | total=৳${Math.round(Number(r.totalPurchase) || 0)} | orders=${r.totalOrders} | 30d=${r.monthlyOrders} | last=${lastTxt}`;
        toInsert.push({
          customer_id: r.id,
          old_segment: prev ?? null,
          new_segment: r.segment,
          reason,
        });
      }
    }
    if (!toInsert.length) return;
    // Fire-and-forget batch insert (chunk to avoid huge payloads)
    (async () => {
      const chunk = 200;
      for (let i = 0; i < toInsert.length; i += chunk) {
        await supabase.from("customer_segment_logs" as any).insert(toInsert.slice(i, i + chunk));
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [rows, latestSegMap]);



  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    return rows.filter((r) => {
      if (filter !== "all" && r.segment !== filter) return false;
      if (!q) return true;
      return (
        String(r.name || "").toLowerCase().includes(q) ||
        String(r.name_bn || "").toLowerCase().includes(q) ||
        String(r.mobile || "").toLowerCase().includes(q)
      );
    });
  }, [rows, search, filter]);

  const isLoading = cLoading || sLoading;

  const exportCSV = () => {
    const header = [
      isBn ? "নাম" : "Name",
      isBn ? "মোবাইল" : "Mobile",
      isBn ? "সেগমেন্ট" : "Segment",
      isBn ? "মোট ক্রয়" : "Total Purchase",
      isBn ? "মোট অর্ডার" : "Total Orders",
      isBn ? "৩০ দিন অর্ডার" : "30d Orders",
      isBn ? "শেষ ক্রয়" : "Last Purchase",
      isBn ? "ওয়ালেট" : "Wallet",
      isBn ? "বকেয়া" : "Due",
    ];
    const lines = [header.join(",")];
    for (const r of filtered) {
      lines.push(
        [
          `"${r.name || ""}"`,
          r.mobile || "",
          r.segment,
          r.totalPurchase,
          r.totalOrders,
          r.monthlyOrders,
          r.lastPurchase ? new Date(r.lastPurchase).toLocaleDateString("en-GB") : "",
          r.wallet,
          r.total_due || 0,
        ].join(","),
      );
    }
    const blob = new Blob([lines.join("\n")], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `customer-segments-${new Date().toISOString().slice(0, 10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
    toast.success(isBn ? "এক্সপোর্ট সম্পন্ন" : "Exported");
  };

  const saveThresholds = (t: SegmentThresholds) => {
    setThresholds(t);
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(t));
    } catch {}
    setShowSettings(false);
    toast.success(isBn ? "সেটিংস সংরক্ষিত" : "Settings saved");
  };

  const cards: { key: CustomerSegment; Icon: any }[] = [
    { key: "vip", Icon: Crown },
    { key: "regular", Icon: UserCheck },
    { key: "new", Icon: Sparkles },
    { key: "inactive", Icon: Moon },
  ];

  return (
    <PageLayout>
      <div className="mb-6 flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-xl font-bold text-foreground">
            {isBn ? "কাস্টমার সেগমেন্টেশন" : "Customer Segmentation"}
          </h1>
          <p className="text-sm text-muted-foreground">
            {isBn
              ? "ক্রয়ের অভ্যাস অনুযায়ী স্বয়ংক্রিয় শ্রেণীবিভাগ"
              : "Auto categorization based on purchase behavior"}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowSettings(true)}
            className="flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium hover:bg-muted"
          >
            <SettingsIcon className="h-4 w-4" />
            {isBn ? "থ্রেশহোল্ড" : "Thresholds"}
          </button>
          <button
            onClick={exportCSV}
            className="flex items-center gap-2 rounded-lg bg-primary px-3 py-2 text-sm font-semibold text-primary-foreground hover:opacity-90"
          >
            <Download className="h-4 w-4" />
            {isBn ? "এক্সপোর্ট" : "Export"}
          </button>
        </div>
      </div>

      {/* Segment summary cards */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
        {cards.map(({ key }) => {
          const m = SEGMENT_META[key];
          const Icon = m.Icon;
          const active = filter === key;
          return (
            <button
              key={key}
              onClick={() => setFilter(active ? "all" : key)}
              className={`text-left rounded-xl border p-4 transition-all hover:shadow ${m.cls} ${active ? "ring-2 ring-offset-2 ring-primary" : ""}`}
            >
              <div className="flex items-center justify-between">
                <div className="text-xs font-semibold uppercase">{isBn ? m.bn : m.en}</div>
                <Icon className="h-4 w-4 opacity-80" />
              </div>
              <div className="mt-2 text-2xl font-bold">{counts[key]}</div>
              <div className="text-[11px] opacity-80">
                {isBn ? "কাস্টমার" : "customers"}
              </div>
            </button>
          );
        })}
      </div>

      {/* Search + filter */}
      <div className="mb-3 flex items-center gap-2 flex-wrap">
        <div className="relative flex-1 min-w-[220px]">
          <Search className="absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder={isBn ? "নাম বা মোবাইল" : "Name or mobile"}
            className="w-full rounded-lg border border-border bg-card pl-8 pr-3 py-2 text-sm"
          />
        </div>
        <button
          onClick={() => setFilter("all")}
          className={`rounded-full border px-3 py-1 text-xs font-medium ${filter === "all" ? "bg-primary text-primary-foreground border-primary" : "bg-card text-foreground border-border hover:bg-muted"}`}
        >
          {isBn ? "সব" : "All"} ({rows.length})
        </button>
      </div>

      <div className="rounded-xl border border-border bg-card overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-border text-left text-xs text-muted-foreground">
              <th className="px-4 py-3 font-medium">{isBn ? "কাস্টমার" : "Customer"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "মোবাইল" : "Mobile"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "সেগমেন্ট" : "Segment"}</th>
              <th className="px-4 py-3 font-medium text-right">{isBn ? "মোট ক্রয়" : "Total Purchase"}</th>
              <th className="px-4 py-3 font-medium text-right">{isBn ? "অর্ডার" : "Orders"}</th>
              <th className="px-4 py-3 font-medium text-right">{isBn ? "৩০ দিন" : "30d"}</th>
              <th className="px-4 py-3 font-medium">{isBn ? "শেষ ক্রয়" : "Last Purchase"}</th>
              <th className="px-4 py-3 font-medium text-right">{isBn ? "ওয়ালেট" : "Wallet"}</th>
              <th className="px-4 py-3 font-medium text-right">{isBn ? "বকেয়া" : "Due"}</th>
              <th className="px-4 py-3 font-medium text-center">{isBn ? "ইতিহাস" : "History"}</th>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr>
                <td colSpan={10} className="px-4 py-8 text-center text-muted-foreground">
                  {isBn ? "লোড হচ্ছে..." : "Loading..."}
                </td>
              </tr>
            ) : filtered.length === 0 ? (
              <tr>
                <td colSpan={10} className="px-4 py-8 text-center text-muted-foreground">
                  {isBn ? "কোনো কাস্টমার নেই" : "No customers"}
                </td>
              </tr>
            ) : (
              filtered.map((r: any) => (
                <tr key={r.id} className="border-b border-border last:border-0 hover:bg-muted/30">
                  <td className="px-4 py-3">
                    <Link
                      to="/customers"
                      className="font-medium text-foreground hover:underline"
                    >
                      {isBn ? r.name_bn || r.name : r.name}
                    </Link>
                  </td>
                  <td className="px-4 py-3 text-xs text-muted-foreground">
                    {r.mobile && (
                      <a
                        href={`tel:${r.mobile}`}
                        className="inline-flex items-center gap-1 hover:text-foreground"
                      >
                        <Phone className="h-3 w-3" />
                        {r.mobile}
                      </a>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <SegmentBadge segment={r.segment} isBn={isBn} />
                  </td>
                  <td className="px-4 py-3 text-right font-semibold">
                    ৳{Number(r.totalPurchase).toLocaleString()}
                  </td>
                  <td className="px-4 py-3 text-right">{r.totalOrders}</td>
                  <td className="px-4 py-3 text-right">{r.monthlyOrders}</td>
                  <td className="px-4 py-3 text-xs text-muted-foreground">
                    {r.lastPurchase
                      ? new Date(r.lastPurchase).toLocaleDateString(isBn ? "bn-BD" : "en-GB")
                      : "—"}
                  </td>
                  <td className="px-4 py-3 text-right text-green-600">
                    ৳{Number(r.wallet).toLocaleString()}
                  </td>
                  <td className="px-4 py-3 text-right text-orange-600">
                    ৳{Number(r.total_due || 0).toLocaleString()}
                  </td>
                  <td className="px-4 py-3 text-center">
                    <button
                      onClick={() => setHistoryCustomer(r)}
                      className="inline-flex items-center gap-1 rounded-md border border-border bg-card px-2 py-1 text-xs hover:bg-muted"
                      title={isBn ? "সেগমেন্ট ইতিহাস" : "Segment History"}
                    >
                      <HistoryIcon className="h-3.5 w-3.5" />
                      {isBn ? "দেখুন" : "View"}
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      <ThresholdsDialog
        open={showSettings}
        onOpenChange={setShowSettings}
        thresholds={thresholds}
        onSave={saveThresholds}
        isBn={isBn}
      />
      <SegmentHistoryDialog
        customer={historyCustomer}
        onClose={() => setHistoryCustomer(null)}
        isBn={isBn}
      />
    </PageLayout>
  );
}

function ThresholdsDialog({
  open,
  onOpenChange,
  thresholds,
  onSave,
  isBn,
}: {
  open: boolean;
  onOpenChange: (v: boolean) => void;
  thresholds: SegmentThresholds;
  onSave: (t: SegmentThresholds) => void;
  isBn: boolean;
}) {
  const [t, setT] = useState(thresholds);
  useEffect(() => setT(thresholds), [thresholds, open]);

  const Row = ({
    label,
    value,
    onChange,
    suffix,
  }: {
    label: string;
    value: number;
    onChange: (v: number) => void;
    suffix: string;
  }) => (
    <div className="flex items-center justify-between gap-3">
      <label className="text-sm">{label}</label>
      <div className="flex items-center gap-2">
        <input
          type="number"
          value={value}
          onChange={(e) => onChange(Number(e.target.value) || 0)}
          className="w-32 rounded-md border border-border bg-card px-2 py-1 text-sm text-right"
        />
        <span className="text-xs text-muted-foreground w-14">{suffix}</span>
      </div>
    </div>
  );

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>
            {isBn ? "সেগমেন্ট থ্রেশহোল্ড" : "Segment Thresholds"}
          </DialogTitle>
        </DialogHeader>
        <div className="space-y-3 py-2">
          <div className="text-xs font-semibold text-amber-600">
            {isBn ? "ভিআইপি কাস্টমার" : "VIP Customer"}
          </div>
          <Row
            label={isBn ? "মোট ক্রয় ≥" : "Total Purchase ≥"}
            value={t.vipTotalPurchase}
            onChange={(v) => setT({ ...t, vipTotalPurchase: v })}
            suffix="৳"
          />
          <Row
            label={isBn ? "মাসিক অর্ডার ≥" : "Monthly Orders ≥"}
            value={t.vipMonthlyOrders}
            onChange={(v) => setT({ ...t, vipMonthlyOrders: v })}
            suffix={isBn ? "টি" : "orders"}
          />
          <div className="text-xs font-semibold text-blue-600 mt-2">
            {isBn ? "নিয়মিত কাস্টমার" : "Regular Customer"}
          </div>
          <Row
            label={isBn ? "মাসিক অর্ডার ≥" : "Monthly Orders ≥"}
            value={t.regularMonthlyOrdersMin}
            onChange={(v) => setT({ ...t, regularMonthlyOrdersMin: v })}
            suffix={isBn ? "টি" : "orders"}
          />
          <div className="text-xs font-semibold text-green-600 mt-2">
            {isBn ? "নতুন কাস্টমার" : "New Customer"}
          </div>
          <Row
            label={isBn ? "রেজিস্ট্রেশন <" : "Registered <"}
            value={t.newCustomerDays}
            onChange={(v) => setT({ ...t, newCustomerDays: v })}
            suffix={isBn ? "দিন" : "days"}
          />
          <div className="text-xs font-semibold text-gray-600 mt-2">
            {isBn ? "নিষ্ক্রিয় কাস্টমার" : "Inactive Customer"}
          </div>
          <Row
            label={isBn ? "শেষ ক্রয় >" : "Last Purchase >"}
            value={t.inactiveDays}
            onChange={(v) => setT({ ...t, inactiveDays: v })}
            suffix={isBn ? "দিন" : "days"}
          />
        </div>
        <DialogFooter>
          <button
            onClick={() => onOpenChange(false)}
            className="rounded-lg border border-border bg-card px-4 py-2 text-sm hover:bg-muted"
          >
            {isBn ? "বাতিল" : "Cancel"}
          </button>
          <button
            onClick={() => onSave(t)}
            className="rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground hover:opacity-90"
          >
            {isBn ? "সংরক্ষণ" : "Save"}
          </button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function SegmentHistoryDialog({
  customer,
  onClose,
  isBn,
}: {
  customer: any | null;
  onClose: () => void;
  isBn: boolean;
}) {
  const { data: logs = [], isLoading } = useQuery({
    queryKey: ["seg-history", customer?.id],
    enabled: !!customer,
    queryFn: async () => {
      const { data, error } = await supabase
        .from("customer_segment_logs" as any)
        .select("id, old_segment, new_segment, reason, created_at")
        .eq("customer_id", customer!.id)
        .order("created_at", { ascending: false })
        .limit(200);
      if (error) return [];
      return (data as any[]) || [];
    },
  });

  return (
    <Dialog open={!!customer} onOpenChange={(v) => !v && onClose()}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>
            {isBn ? "সেগমেন্ট ইতিহাস" : "Segment History"} —{" "}
            <span className="text-primary">
              {customer && (isBn ? customer.name_bn || customer.name : customer.name)}
            </span>
          </DialogTitle>
        </DialogHeader>
        <div className="max-h-[60vh] overflow-y-auto">
          {isLoading ? (
            <p className="py-6 text-center text-sm text-muted-foreground">
              {isBn ? "লোড হচ্ছে..." : "Loading..."}
            </p>
          ) : logs.length === 0 ? (
            <p className="py-6 text-center text-sm text-muted-foreground">
              {isBn
                ? "এখনো কোনো সেগমেন্ট পরিবর্তন রেকর্ড হয়নি"
                : "No segment changes recorded yet"}
            </p>
          ) : (
            <ol className="relative border-l border-border ml-3 space-y-4 py-2">
              {(logs as any[]).map((l) => (
                <li key={l.id} className="ml-4">
                  <span className="absolute -left-1.5 mt-1.5 h-3 w-3 rounded-full bg-primary border border-background" />
                  <div className="flex items-center gap-2 flex-wrap">
                    {l.old_segment ? (
                      <SegmentBadge segment={l.old_segment} isBn={isBn} />
                    ) : (
                      <span className="text-xs text-muted-foreground italic">
                        {isBn ? "শুরু" : "initial"}
                      </span>
                    )}
                    <span className="text-muted-foreground">→</span>
                    <SegmentBadge segment={l.new_segment} isBn={isBn} />
                    <span className="ml-2 text-xs text-muted-foreground">
                      {new Date(l.created_at).toLocaleString(isBn ? "bn-BD" : "en-GB")}
                    </span>
                  </div>
                  {l.reason && (
                    <p className="mt-1 text-xs text-muted-foreground font-mono break-all">
                      {l.reason}
                    </p>
                  )}
                </li>
              ))}
            </ol>
          )}
        </div>
      </DialogContent>
    </Dialog>
  );
}
