import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useEffect, useMemo, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Building2, Package, AlertTriangle, TrendingUp, Download } from "lucide-react";
import { exportCSV, exportXLSX, exportPDF } from "@/lib/export-utils";

export const Route = createFileRoute("/_authenticated/branch-reports")({
  head: () => ({ meta: [{ title: "Branch Reports — Niyamah ERP" }] }),
  component: BranchReportsPage,
});

type Branch = { id: string; name: string; code: string; status: string };
type Product = { id: string; name: string; sku: string; branch_id: string | null; stock_quantity: number; purchase_price: number; retail_price: number };
type SaleTx = { id: string; branch_id: string | null; amount: number; created_at: string };

function BranchReportsPage() {
  const { tr, lang } = useLanguage();
  const isBn = lang === "bn";
  const [branches, setBranches] = useState<Branch[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [sales, setSales] = useState<SaleTx[]>([]);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState<"stock" | "sales">("stock");
  const [branchFilter, setBranchFilter] = useState<string>("all");
  const [fromDate, setFromDate] = useState<string>(() => {
    const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10);
  });
  const [toDate, setToDate] = useState<string>(() => new Date().toISOString().slice(0, 10));

  useEffect(() => {
    (async () => {
      setLoading(true);
      const [b, p] = await Promise.all([
        supabase.from("branches").select("id,name,code,status").is("deleted_at", null).order("name"),
        supabase.from("products").select("id,name,sku,branch_id,stock_quantity,purchase_price,retail_price").eq("is_deleted", false),
      ]);
      setBranches((b.data as Branch[]) || []);
      setProducts((p.data as Product[]) || []);
      setLoading(false);
    })();
  }, []);

  useEffect(() => {
    (async () => {
      const { data } = await supabase
        .from("customer_transactions")
        .select("id,branch_id,amount,created_at")
        .eq("type", "sale")
        .gte("created_at", `${fromDate}T00:00:00`)
        .lte("created_at", `${toDate}T23:59:59`);
      setSales((data as SaleTx[]) || []);
    })();
  }, [fromDate, toDate]);

  // Stock summary per branch
  const stockSummary = useMemo(() => {
    const map = new Map<string, { branch: Branch | null; products: number; units: number; value: number; lowStock: number }>();
    const ensure = (id: string | null) => {
      const key = id || "__none__";
      if (!map.has(key)) {
        const branch = branches.find((b) => b.id === id) || null;
        map.set(key, { branch, products: 0, units: 0, value: 0, lowStock: 0 });
      }
      return map.get(key)!;
    };
    branches.forEach((b) => ensure(b.id));
    products.forEach((p) => {
      const row = ensure(p.branch_id);
      row.products += 1;
      row.units += Number(p.stock_quantity) || 0;
      row.value += (Number(p.stock_quantity) || 0) * (Number(p.purchase_price) || 0);
      if ((Number(p.stock_quantity) || 0) <= 5) row.lowStock += 1;
    });
    return Array.from(map.values()).filter((r) => branchFilter === "all" || r.branch?.id === branchFilter);
  }, [branches, products, branchFilter]);

  // Sales summary per branch
  const salesSummary = useMemo(() => {
    const map = new Map<string, { branch: Branch | null; count: number; total: number }>();
    const ensure = (id: string | null) => {
      const key = id || "__none__";
      if (!map.has(key)) {
        const branch = branches.find((b) => b.id === id) || null;
        map.set(key, { branch, count: 0, total: 0 });
      }
      return map.get(key)!;
    };
    branches.forEach((b) => ensure(b.id));
    sales.forEach((s) => {
      const row = ensure(s.branch_id);
      row.count += 1;
      row.total += Number(s.amount) || 0;
    });
    return Array.from(map.values()).filter((r) => branchFilter === "all" || r.branch?.id === branchFilter);
  }, [branches, sales, branchFilter]);

  // Branch-wise product detail (for stock tab)
  const filteredProducts = useMemo(() => {
    return products.filter((p) => branchFilter === "all" || p.branch_id === branchFilter);
  }, [products, branchFilter]);

  const totals = useMemo(() => ({
    branches: branches.length,
    products: filteredProducts.length,
    units: filteredProducts.reduce((a, p) => a + (Number(p.stock_quantity) || 0), 0),
    value: filteredProducts.reduce((a, p) => a + (Number(p.stock_quantity) || 0) * (Number(p.purchase_price) || 0), 0),
    sales: salesSummary.reduce((a, r) => a + r.total, 0),
    salesCount: salesSummary.reduce((a, r) => a + r.count, 0),
  }), [branches, filteredProducts, salesSummary]);

  const exportRows = () => {
    if (tab === "stock") {
      return stockSummary.map((r) => ({
        Branch: r.branch?.name || (isBn ? "অনির্ধারিত" : "Unassigned"),
        Code: r.branch?.code || "",
        Products: r.products,
        Units: r.units,
        "Stock Value": r.value.toFixed(2),
        "Low Stock": r.lowStock,
      }));
    }
    return salesSummary.map((r) => ({
      Branch: r.branch?.name || (isBn ? "অনির্ধারিত" : "Unassigned"),
      Code: r.branch?.code || "",
      "Sales Count": r.count,
      "Total Sales": r.total.toFixed(2),
    }));
  };

  const inputCls = "rounded-lg border border-input bg-card px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring";

  return (
    <PageLayout>
      <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1 className="text-xl font-bold text-foreground">{isBn ? "শাখাভিত্তিক রিপোর্ট" : "Branch Reports"}</h1>
          <p className="text-sm text-muted-foreground">{isBn ? "শাখা অনুযায়ী স্টক ও বিক্রয়" : "Stock & Sales by branch"}</p>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          <button onClick={() => exportCSV(`branch-${tab}-report`, exportRows())} className="flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-2 text-xs font-medium hover:bg-muted">
            <Download className="h-3.5 w-3.5" /> CSV
          </button>
          <button onClick={() => exportXLSX(`branch-${tab}-report`, exportRows())} className="flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-2 text-xs font-medium hover:bg-muted">
            <Download className="h-3.5 w-3.5" /> Excel
          </button>
          <button onClick={() => exportPDF(`branch-${tab}-report`, isBn ? "শাখাভিত্তিক রিপোর্ট" : "Branch Report", exportRows())} className="flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-2 text-xs font-medium hover:bg-muted">
            <Download className="h-3.5 w-3.5" /> PDF
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="mb-4 flex flex-wrap items-center gap-2">
        <select className={inputCls} value={branchFilter} onChange={(e) => setBranchFilter(e.target.value)}>
          <option value="all">{isBn ? "সব শাখা" : "All Branches"}</option>
          {branches.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
        </select>
        {tab === "sales" && (
          <>
            <input type="date" className={inputCls} value={fromDate} onChange={(e) => setFromDate(e.target.value)} />
            <span className="text-sm text-muted-foreground">→</span>
            <input type="date" className={inputCls} value={toDate} onChange={(e) => setToDate(e.target.value)} />
          </>
        )}
      </div>

      {/* KPI cards */}
      <div className="mb-6 grid grid-cols-2 gap-3 md:grid-cols-4">
        <KPI icon={Building2} label={isBn ? "শাখা" : "Branches"} value={totals.branches} />
        <KPI icon={Package} label={isBn ? "মোট পণ্য" : "Products"} value={totals.products} />
        <KPI icon={TrendingUp} label={isBn ? "স্টক মূল্য (৳)" : "Stock Value (৳)"} value={totals.value.toFixed(0)} />
        <KPI icon={TrendingUp} label={isBn ? "মোট বিক্রয় (৳)" : "Total Sales (৳)"} value={totals.sales.toFixed(0)} />
      </div>

      {/* Tabs */}
      <div className="mb-4 flex gap-2 border-b border-border">
        <TabBtn active={tab === "stock"} onClick={() => setTab("stock")}>{isBn ? "স্টক রিপোর্ট" : "Stock Report"}</TabBtn>
        <TabBtn active={tab === "sales"} onClick={() => setTab("sales")}>{isBn ? "বিক্রয় রিপোর্ট" : "Sales Report"}</TabBtn>
      </div>

      {loading ? (
        <div className="flex h-40 items-center justify-center text-muted-foreground">{isBn ? "লোড হচ্ছে..." : "Loading..."}</div>
      ) : tab === "stock" ? (
        <div className="space-y-6">
          <div className="overflow-hidden rounded-xl border border-border bg-card">
            <div className="border-b border-border px-4 py-3 text-sm font-semibold">{isBn ? "শাখা সারাংশ" : "Branch Summary"}</div>
            <table className="w-full text-sm">
              <thead className="bg-muted/50 text-xs text-muted-foreground">
                <tr>
                  <th className="px-4 py-2.5 text-left">{tr("branchName")}</th>
                  <th className="px-4 py-2.5 text-right">{isBn ? "পণ্য" : "Products"}</th>
                  <th className="px-4 py-2.5 text-right">{isBn ? "ইউনিট" : "Units"}</th>
                  <th className="px-4 py-2.5 text-right">{isBn ? "স্টক মূল্য (৳)" : "Stock Value (৳)"}</th>
                  <th className="px-4 py-2.5 text-right">{isBn ? "কম স্টক" : "Low Stock"}</th>
                </tr>
              </thead>
              <tbody>
                {stockSummary.map((r, i) => (
                  <tr key={i} className="border-t border-border hover:bg-muted/30">
                    <td className="px-4 py-2.5">
                      <div className="flex items-center gap-2">
                        <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-primary/10"><Building2 className="h-3.5 w-3.5 text-primary" /></div>
                        <span className="font-medium">{r.branch?.name || (isBn ? "অনির্ধারিত" : "Unassigned")}</span>
                        {r.branch?.code && <span className="font-mono text-xs text-muted-foreground">({r.branch.code})</span>}
                      </div>
                    </td>
                    <td className="px-4 py-2.5 text-right">{r.products}</td>
                    <td className="px-4 py-2.5 text-right">{r.units}</td>
                    <td className="px-4 py-2.5 text-right font-medium">৳{r.value.toLocaleString()}</td>
                    <td className="px-4 py-2.5 text-right">
                      {r.lowStock > 0 ? (
                        <span className="inline-flex items-center gap-1 rounded-full bg-yellow-100 px-2 py-0.5 text-xs text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400">
                          <AlertTriangle className="h-3 w-3" /> {r.lowStock}
                        </span>
                      ) : <span className="text-muted-foreground">—</span>}
                    </td>
                  </tr>
                ))}
                {stockSummary.length === 0 && <tr><td colSpan={5} className="py-8 text-center text-muted-foreground">{isBn ? "কোনো ডেটা নেই" : "No data"}</td></tr>}
              </tbody>
            </table>
          </div>

          <div className="overflow-hidden rounded-xl border border-border bg-card">
            <div className="border-b border-border px-4 py-3 text-sm font-semibold">{isBn ? "পণ্য বিস্তারিত" : "Product Details"}</div>
            <div className="max-h-[500px] overflow-auto">
              <table className="w-full text-sm">
                <thead className="sticky top-0 bg-muted/50 text-xs text-muted-foreground">
                  <tr>
                    <th className="px-4 py-2.5 text-left">{isBn ? "পণ্য" : "Product"}</th>
                    <th className="px-4 py-2.5 text-left">SKU</th>
                    <th className="px-4 py-2.5 text-left">{tr("branchName")}</th>
                    <th className="px-4 py-2.5 text-right">{isBn ? "স্টক" : "Stock"}</th>
                    <th className="px-4 py-2.5 text-right">{isBn ? "ক্রয় মূল্য" : "Purchase"}</th>
                    <th className="px-4 py-2.5 text-right">{isBn ? "মূল্য" : "Value"}</th>
                  </tr>
                </thead>
                <tbody>
                  {filteredProducts.map((p) => {
                    const branch = branches.find((b) => b.id === p.branch_id);
                    return (
                      <tr key={p.id} className="border-t border-border hover:bg-muted/30">
                        <td className="px-4 py-2.5">{p.name}</td>
                        <td className="px-4 py-2.5 font-mono text-xs text-muted-foreground">{p.sku}</td>
                        <td className="px-4 py-2.5 text-muted-foreground">{branch?.name || "—"}</td>
                        <td className="px-4 py-2.5 text-right">{p.stock_quantity}</td>
                        <td className="px-4 py-2.5 text-right">৳{p.purchase_price}</td>
                        <td className="px-4 py-2.5 text-right font-medium">৳{((p.stock_quantity || 0) * (p.purchase_price || 0)).toLocaleString()}</td>
                      </tr>
                    );
                  })}
                  {filteredProducts.length === 0 && <tr><td colSpan={6} className="py-8 text-center text-muted-foreground">{isBn ? "কোনো পণ্য নেই" : "No products"}</td></tr>}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      ) : (
        <div className="overflow-hidden rounded-xl border border-border bg-card">
          <div className="border-b border-border px-4 py-3 text-sm font-semibold">
            {isBn ? "শাখাভিত্তিক বিক্রয়" : "Branch-wise Sales"} ({fromDate} → {toDate})
          </div>
          <table className="w-full text-sm">
            <thead className="bg-muted/50 text-xs text-muted-foreground">
              <tr>
                <th className="px-4 py-2.5 text-left">{tr("branchName")}</th>
                <th className="px-4 py-2.5 text-right">{isBn ? "বিক্রয় সংখ্যা" : "Sales Count"}</th>
                <th className="px-4 py-2.5 text-right">{isBn ? "মোট পরিমাণ (৳)" : "Total Amount (৳)"}</th>
                <th className="px-4 py-2.5 text-right">{isBn ? "গড় (৳)" : "Average (৳)"}</th>
              </tr>
            </thead>
            <tbody>
              {salesSummary.map((r, i) => (
                <tr key={i} className="border-t border-border hover:bg-muted/30">
                  <td className="px-4 py-2.5">
                    <div className="flex items-center gap-2">
                      <div className="flex h-7 w-7 items-center justify-center rounded-lg bg-primary/10"><Building2 className="h-3.5 w-3.5 text-primary" /></div>
                      <span className="font-medium">{r.branch?.name || (isBn ? "অনির্ধারিত" : "Unassigned")}</span>
                    </div>
                  </td>
                  <td className="px-4 py-2.5 text-right">{r.count}</td>
                  <td className="px-4 py-2.5 text-right font-medium">৳{r.total.toLocaleString()}</td>
                  <td className="px-4 py-2.5 text-right text-muted-foreground">৳{r.count ? (r.total / r.count).toFixed(0) : 0}</td>
                </tr>
              ))}
              {salesSummary.length === 0 && <tr><td colSpan={4} className="py-8 text-center text-muted-foreground">{isBn ? "এই সময়ে কোনো বিক্রয় নেই" : "No sales in this period"}</td></tr>}
            </tbody>
          </table>
          {totals.salesCount === 0 && (
            <div className="border-t border-border bg-muted/20 px-4 py-3 text-xs text-muted-foreground">
              💡 {isBn
                ? "নোট: বিক্রয়ে শাখা ট্যাগিং সক্রিয় করার জন্য Sale তৈরির সময় branch_id সেভ করতে হবে।"
                : "Note: To enable branch tagging on sales, save branch_id when creating each sale."}
            </div>
          )}
        </div>
      )}
    </PageLayout>
  );
}

function KPI({ icon: Icon, label, value }: { icon: any; label: string; value: number | string }) {
  return (
    <div className="rounded-xl border border-border bg-card p-4">
      <div className="flex items-center justify-between">
        <span className="text-xs text-muted-foreground">{label}</span>
        <Icon className="h-4 w-4 text-muted-foreground" />
      </div>
      <div className="mt-2 text-xl font-bold text-foreground">{value}</div>
    </div>
  );
}

function TabBtn({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
  return (
    <button onClick={onClick} className={`border-b-2 px-4 py-2 text-sm font-medium transition-colors ${active ? "border-primary text-primary" : "border-transparent text-muted-foreground hover:text-foreground"}`}>
      {children}
    </button>
  );
}
