import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useAuth } from "@/hooks/use-auth";
import { useMemo, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useQuery } from "@tanstack/react-query";
import { Wallet, Search, ShieldAlert, FileSpreadsheet, FileText, Download, ArrowUpDown } from "lucide-react";
import { exportCSV, exportXLSX, exportPDF } from "@/lib/export-utils";

export const Route = createFileRoute("/_authenticated/wallet-report")({
  head: () => ({ meta: [{ title: "Wallet Report — Niyamah ERP" }] }),
  component: WalletReportPage,
});

type Row = {
  customer_id: string;
  name: string;
  name_bn: string;
  mobile: string;
  total_commission: number;
  paid_amount: number;
  adjusted_amount: number;
  balance: number;
};

type SortKey = "name" | "balance" | "total_commission" | "paid_amount" | "adjusted_amount";

function WalletReportPage() {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const { user } = useAuth();

  const { data: isAdmin = false } = useQuery({
    queryKey: ["is-admin", user?.id],
    enabled: !!user?.id,
    queryFn: async () => {
      const { data } = await supabase.from("user_roles").select("role").eq("user_id", user!.id).eq("role", "admin").maybeSingle();
      return !!data;
    },
  });

  const [search, setSearch] = useState("");
  const [onlyNonZero, setOnlyNonZero] = useState(false);
  const [sortKey, setSortKey] = useState<SortKey>("balance");
  const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");

  const { data: rows = [], isLoading } = useQuery({
    queryKey: ["wallet-report-all"],
    enabled: isAdmin,
    queryFn: async () => {
      const { data: wallets } = await supabase
        .from("referral_wallets")
        .select("customer_id, total_commission, paid_amount, adjusted_amount, balance")
        .limit(5000);
      const ids = (wallets || []).map((w: any) => w.customer_id);
      if (ids.length === 0) return [] as Row[];
      const { data: customers } = await supabase
        .from("customers")
        .select("id, name, name_bn, mobile")
        .in("id", ids);
      const cmap = new Map((customers || []).map((c: any) => [c.id, c]));
      return (wallets || []).map((w: any) => {
        const c: any = cmap.get(w.customer_id) || {};
        return {
          customer_id: w.customer_id,
          name: c.name || "—",
          name_bn: c.name_bn || "",
          mobile: c.mobile || "",
          total_commission: Number(w.total_commission || 0),
          paid_amount: Number(w.paid_amount || 0),
          adjusted_amount: Number(w.adjusted_amount || 0),
          balance: Number(w.balance || 0),
        } as Row;
      });
    },
  });

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    let r = rows.filter((x) => {
      if (onlyNonZero && x.balance === 0 && x.total_commission === 0) return false;
      if (!q) return true;
      return (
        x.name.toLowerCase().includes(q) ||
        x.name_bn.toLowerCase().includes(q) ||
        x.mobile.toLowerCase().includes(q)
      );
    });
    r = [...r].sort((a, b) => {
      const av = a[sortKey] as any;
      const bv = b[sortKey] as any;
      if (typeof av === "string") {
        return sortDir === "asc" ? av.localeCompare(bv) : bv.localeCompare(av);
      }
      return sortDir === "asc" ? av - bv : bv - av;
    });
    return r;
  }, [rows, search, onlyNonZero, sortKey, sortDir]);

  const totals = useMemo(() => {
    return filtered.reduce(
      (acc, r) => {
        acc.total_commission += r.total_commission;
        acc.paid_amount += r.paid_amount;
        acc.adjusted_amount += r.adjusted_amount;
        acc.balance += r.balance;
        return acc;
      },
      { total_commission: 0, paid_amount: 0, adjusted_amount: 0, balance: 0 },
    );
  }, [filtered]);

  const toggleSort = (k: SortKey) => {
    if (sortKey === k) setSortDir((d) => (d === "asc" ? "desc" : "asc"));
    else { setSortKey(k); setSortDir("desc"); }
  };

  const exportRows = () =>
    filtered.map((r) => ({
      [isBn ? "নাম" : "Name"]: isBn ? r.name_bn || r.name : r.name,
      [isBn ? "মোবাইল" : "Mobile"]: r.mobile,
      [isBn ? "মোট কমিশন" : "Total Commission"]: r.total_commission.toFixed(2),
      [isBn ? "পরিশোধিত" : "Paid"]: r.paid_amount.toFixed(2),
      [isBn ? "সমন্বয়" : "Adjusted"]: r.adjusted_amount.toFixed(2),
      [isBn ? "ব্যালেন্স" : "Balance"]: r.balance.toFixed(2),
    }));

  if (!isAdmin) {
    return (
      <PageLayout>
        <div className="rounded-2xl border border-destructive/30 bg-destructive/5 p-8 text-center">
          <ShieldAlert className="h-10 w-10 mx-auto text-destructive mb-2" />
          <h1 className="text-xl font-bold">{isBn ? "অনুমতি নেই" : "Permission denied"}</h1>
          <p className="text-sm text-muted-foreground mt-1">{isBn ? "শুধু অ্যাডমিন এই পেজ ব্যবহার করতে পারবেন" : "Only admins can access this page"}</p>
        </div>
      </PageLayout>
    );
  }

  return (
    <PageLayout>
      <div className="mb-6 flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2">
            <Wallet className="h-6 w-6 text-primary" />
            {isBn ? "ওয়ালেট রিপোর্ট" : "Wallet Report"}
          </h1>
          <p className="text-sm text-muted-foreground">
            {isBn ? "সকল কাস্টমারের ওয়ালেট ব্যালেন্স ও কমিশন" : "All customer wallet balances and commissions"}
          </p>
        </div>
        <div className="flex gap-2 flex-wrap">
          <button onClick={() => exportCSV("wallet-report", exportRows())} className="rounded-lg border border-border bg-background px-3 py-2 text-sm flex items-center gap-1">
            <Download className="h-4 w-4" /> CSV
          </button>
          <button onClick={() => exportXLSX("wallet-report", exportRows())} className="rounded-lg border border-border bg-background px-3 py-2 text-sm flex items-center gap-1">
            <FileSpreadsheet className="h-4 w-4" /> Excel
          </button>
          <button onClick={() => exportPDF("wallet-report", isBn ? "ওয়ালেট রিপোর্ট" : "Wallet Report", exportRows())} className="rounded-lg border border-border bg-background px-3 py-2 text-sm flex items-center gap-1">
            <FileText className="h-4 w-4" /> PDF
          </button>
        </div>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-6">
        <Stat label={isBn ? "মোট কমিশন" : "Total Commission"} value={totals.total_commission} color="text-primary" />
        <Stat label={isBn ? "পরিশোধিত" : "Paid"} value={totals.paid_amount} color="text-muted-foreground" />
        <Stat label={isBn ? "সমন্বয়" : "Adjusted"} value={totals.adjusted_amount} color="text-amber-600" />
        <Stat label={isBn ? "মোট ব্যালেন্স" : "Total Balance"} value={totals.balance} color="text-green-600" />
      </div>

      <div className="rounded-2xl border border-border bg-card p-4 mb-4 flex flex-wrap items-center gap-3">
        <div className="relative flex-1 min-w-[220px]">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-lg border border-input bg-background pl-9 pr-3 py-2 text-sm"
            placeholder={isBn ? "নাম বা মোবাইল দিয়ে সার্চ" : "Search name or mobile"}
          />
        </div>
        <label className="flex items-center gap-2 text-sm">
          <input type="checkbox" checked={onlyNonZero} onChange={(e) => setOnlyNonZero(e.target.checked)} />
          {isBn ? "শুধু অ্যাক্টিভ ওয়ালেট" : "Only active wallets"}
        </label>
        <span className="text-xs text-muted-foreground ml-auto">
          {isBn ? `${filtered.length} জন কাস্টমার` : `${filtered.length} customers`}
        </span>
      </div>

      <div className="rounded-2xl border border-border bg-card overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead className="bg-muted/40 text-xs">
              <tr className="text-left">
                <Th onClick={() => toggleSort("name")} active={sortKey === "name"}>{isBn ? "কাস্টমার" : "Customer"}</Th>
                <th className="px-3 py-2">{isBn ? "মোবাইল" : "Mobile"}</th>
                <Th onClick={() => toggleSort("total_commission")} active={sortKey === "total_commission"} align="right">{isBn ? "মোট কমিশন" : "Earned"}</Th>
                <Th onClick={() => toggleSort("paid_amount")} active={sortKey === "paid_amount"} align="right">{isBn ? "পরিশোধিত" : "Paid"}</Th>
                <Th onClick={() => toggleSort("adjusted_amount")} active={sortKey === "adjusted_amount"} align="right">{isBn ? "সমন্বয়" : "Adjusted"}</Th>
                <Th onClick={() => toggleSort("balance")} active={sortKey === "balance"} align="right">{isBn ? "ব্যালেন্স" : "Balance"}</Th>
              </tr>
            </thead>
            <tbody>
              {isLoading && (
                <tr><td colSpan={6} className="px-3 py-8 text-center text-xs text-muted-foreground">{isBn ? "লোড হচ্ছে…" : "Loading…"}</td></tr>
              )}
              {!isLoading && filtered.length === 0 && (
                <tr><td colSpan={6} className="px-3 py-8 text-center text-xs text-muted-foreground">{isBn ? "কোনো তথ্য নেই" : "No data"}</td></tr>
              )}
              {filtered.map((r) => (
                <tr key={r.customer_id} className="border-t border-border hover:bg-muted/30">
                  <td className="px-3 py-2 font-medium">{isBn ? r.name_bn || r.name : r.name}</td>
                  <td className="px-3 py-2 text-xs text-muted-foreground">{r.mobile}</td>
                  <td className="px-3 py-2 text-right">৳{r.total_commission.toFixed(2)}</td>
                  <td className="px-3 py-2 text-right text-muted-foreground">৳{r.paid_amount.toFixed(2)}</td>
                  <td className="px-3 py-2 text-right text-amber-600">৳{r.adjusted_amount.toFixed(2)}</td>
                  <td className="px-3 py-2 text-right font-semibold text-green-600">৳{r.balance.toFixed(2)}</td>
                </tr>
              ))}
            </tbody>
            {filtered.length > 0 && (
              <tfoot className="bg-muted/40 text-xs font-semibold">
                <tr>
                  <td className="px-3 py-2" colSpan={2}>{isBn ? "মোট" : "Total"}</td>
                  <td className="px-3 py-2 text-right">৳{totals.total_commission.toFixed(2)}</td>
                  <td className="px-3 py-2 text-right">৳{totals.paid_amount.toFixed(2)}</td>
                  <td className="px-3 py-2 text-right">৳{totals.adjusted_amount.toFixed(2)}</td>
                  <td className="px-3 py-2 text-right text-green-700">৳{totals.balance.toFixed(2)}</td>
                </tr>
              </tfoot>
            )}
          </table>
        </div>
      </div>
    </PageLayout>
  );
}

function Stat({ label, value, color }: { label: string; value: number; color: string }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4">
      <p className="text-xs text-muted-foreground">{label}</p>
      <p className={`mt-1 text-lg font-bold ${color}`}>৳{value.toFixed(2)}</p>
    </div>
  );
}

function Th({ children, onClick, active, align }: { children: React.ReactNode; onClick: () => void; active: boolean; align?: "right" }) {
  return (
    <th className={`px-3 py-2 ${align === "right" ? "text-right" : "text-left"}`}>
      <button onClick={onClick} className={`inline-flex items-center gap-1 ${active ? "text-foreground" : "text-muted-foreground"}`}>
        {children}
        <ArrowUpDown className="h-3 w-3" />
      </button>
    </th>
  );
}
