import { createFileRoute, Link } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useLanguage } from "@/hooks/use-language";
import { useState, useEffect, useMemo } from "react";
import { supabase } from "@/integrations/supabase/client";
import { exportCSV, exportXLSX, exportPDF } from "@/lib/export-utils";
import {
  Package, Layers, TrendingUp, ShoppingCart, Boxes,
  UserCheck, Truck, Receipt, Wallet, Building2, Warehouse, AlertTriangle,
  FileSpreadsheet, FileText, Download, Calendar, Banknote,
} from "lucide-react";

export const Route = createFileRoute("/_authenticated/reports")({
  head: () => ({
    meta: [
      { title: "Reports — Niyamah Electric & Hardware" },
      { name: "description", content: "Business reports" },
    ],
  }),
  component: ReportsPage,
});

type TypeStat = {
  id: string;
  name: string;
  name_bn: string;
  icon: string;
  productCount: number;
  totalStockValue: number;
  avgRetailPrice: number;
  color: string;
  bgClass: string;
};

const TYPE_COLORS: Record<string, { color: string; bgClass: string }> = {
  electric: {
    color: "#eab308",
    bgClass: "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400",
  },
  hardware: {
    color: "#3b82f6",
    bgClass: "bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400",
  },
};

const FALLBACK_COLORS = [
  { color: "#8b5cf6", bgClass: "bg-violet-100 text-violet-800 dark:bg-violet-900/30 dark:text-violet-400" },
  { color: "#10b981", bgClass: "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-400" },
  { color: "#f97316", bgClass: "bg-orange-100 text-orange-800 dark:bg-orange-900/30 dark:text-orange-400" },
];

function ReportsPage() {
  const { tr, lang } = useLanguage();
  const [typeStats, setTypeStats] = useState<TypeStat[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      setLoading(true);
      const [{ data: types }, { data: products }] = await Promise.all([
        supabase.from("product_types").select("*").is("deleted_at", null),
        supabase.from("products").select("product_type_id, retail_price, stock_quantity").eq("is_deleted", false),
      ]);

      if (types && products) {
        let colorIdx = 0;
        const stats: TypeStat[] = types.map((t) => {
          const matched = products.filter((p) => p.product_type_id === t.id);
          const totalStockValue = matched.reduce(
            (sum, p) => sum + Number(p.retail_price) * Number(p.stock_quantity),
            0
          );
          const avgRetailPrice =
            matched.length > 0
              ? matched.reduce((s, p) => s + Number(p.retail_price), 0) / matched.length
              : 0;

          const key = t.name.toLowerCase();
          const colors = TYPE_COLORS[key] || FALLBACK_COLORS[colorIdx++ % FALLBACK_COLORS.length];

          return {
            id: t.id,
            name: t.name,
            name_bn: t.name_bn,
            icon: t.icon,
            productCount: matched.length,
            totalStockValue,
            avgRetailPrice,
            ...colors,
          };
        });
        setTypeStats(stats);
      }
      setLoading(false);
    })();
  }, []);

  const totalProducts = useMemo(() => typeStats.reduce((s, t) => s + t.productCount, 0), [typeStats]);
  const totalValue = useMemo(() => typeStats.reduce((s, t) => s + t.totalStockValue, 0), [typeStats]);
  const maxCount = useMemo(() => Math.max(...typeStats.map((t) => t.productCount), 1), [typeStats]);
  const maxValue = useMemo(() => Math.max(...typeStats.map((t) => t.totalStockValue), 1), [typeStats]);

  // ===== Detailed Reports: date filter + tabs + export =====
  const today = new Date().toISOString().slice(0, 10);
  const monthAgo = new Date(Date.now() - 29 * 86400000).toISOString().slice(0, 10);
  const [fromDate, setFromDate] = useState(monthAgo);
  const [toDate, setToDate] = useState(today);
  const [reportTab, setReportTab] = useState<"sales" | "purchase" | "expense" | "pnl" | "cash_closing">("sales");
  const [reportRows, setReportRows] = useState<any[]>([]);
  const [reportLoading, setReportLoading] = useState(false);
  const [reportTotals, setReportTotals] = useState({ count: 0, total: 0, paid: 0, due: 0 });

  useEffect(() => {
    (async () => {
      setReportLoading(true);
      try {
        if (reportTab === "sales") {
          const { data } = await supabase
            .from("sales")
            .select("invoice_no, sale_date, customer_name, customer_mobile, total_amount, paid_amount, due_amount, payment_method")
            .gte("sale_date", fromDate).lte("sale_date", toDate)
            .order("sale_date", { ascending: false });
          const rows = data || [];
          setReportRows(rows);
          setReportTotals({
            count: rows.length,
            total: rows.reduce((s, r: any) => s + Number(r.total_amount || 0), 0),
            paid: rows.reduce((s, r: any) => s + Number(r.paid_amount || 0), 0),
            due: rows.reduce((s, r: any) => s + Number(r.due_amount || 0), 0),
          });
        } else if (reportTab === "purchase") {
          const { data } = await supabase
            .from("purchases")
            .select("invoice_no, purchase_date, supplier_id, total_amount, paid_amount, due_amount, payment_method")
            .gte("purchase_date", fromDate).lte("purchase_date", toDate)
            .order("purchase_date", { ascending: false });
          const supplierIds = Array.from(new Set((data || []).map((r: any) => r.supplier_id).filter(Boolean)));
          const { data: sups } = supplierIds.length
            ? await supabase.from("suppliers").select("id, name").in("id", supplierIds)
            : { data: [] as any[] };
          const supMap = new Map((sups || []).map((s: any) => [s.id, s.name]));
          const rows = (data || []).map((r: any) => ({
            ...r, supplier_name: supMap.get(r.supplier_id) || "",
          }));
          setReportRows(rows);
          setReportTotals({
            count: rows.length,
            total: rows.reduce((s, r: any) => s + Number(r.total_amount || 0), 0),
            paid: rows.reduce((s, r: any) => s + Number(r.paid_amount || 0), 0),
            due: rows.reduce((s, r: any) => s + Number(r.due_amount || 0), 0),
          });
        } else if (reportTab === "expense") {
          const { data } = await supabase
            .from("expenses")
            .select("expense_date, category, amount, payment_method, note")
            .gte("expense_date", fromDate).lte("expense_date", toDate)
            .order("expense_date", { ascending: false });
          const rows = data || [];
          setReportRows(rows);
          setReportTotals({
            count: rows.length,
            total: rows.reduce((s, r: any) => s + Number(r.amount || 0), 0),
            paid: 0, due: 0,
          });
        } else if (reportTab === "cash_closing") {
          const { data } = await supabase
            .from("daily_cash_closings")
            .select("closing_date, branch_id, shift, opening_cash, cash_sales, due_collection, expense_amount, supplier_payment, bank_deposit, withdraw_amount, expected_cash, closing_cash, difference, is_locked")
            .gte("closing_date", fromDate).lte("closing_date", toDate)
            .order("closing_date", { ascending: false });
          const branchIds = Array.from(new Set((data || []).map((r: any) => r.branch_id).filter(Boolean)));
          const { data: brs } = branchIds.length
            ? await supabase.from("branches").select("id, name").in("id", branchIds)
            : { data: [] as any[] };
          const brMap = new Map((brs || []).map((b: any) => [b.id, b.name]));
          const rows = (data || []).map((r: any) => ({ ...r, branch_name: brMap.get(r.branch_id) || "—" }));
          setReportRows(rows);
          setReportTotals({
            count: rows.length,
            total: rows.reduce((s, r: any) => s + Number(r.cash_sales || 0) + Number(r.due_collection || 0), 0),
            paid: rows.reduce((s, r: any) => s + Number(r.expense_amount || 0) + Number(r.supplier_payment || 0) + Number(r.bank_deposit || 0), 0),
            due: rows.reduce((s, r: any) => s + Number(r.difference || 0), 0),
          });
        } else {
          // P&L: sales - purchases - expenses by date
          const [{ data: s }, { data: p }, { data: e }, { data: i }] = await Promise.all([
            supabase.from("sales").select("sale_date, total_amount").gte("sale_date", fromDate).lte("sale_date", toDate),
            supabase.from("purchases").select("purchase_date, total_amount").gte("purchase_date", fromDate).lte("purchase_date", toDate),
            supabase.from("expenses").select("expense_date, amount").gte("expense_date", fromDate).lte("expense_date", toDate),
            supabase.from("incomes").select("income_date, amount").gte("income_date", fromDate).lte("income_date", toDate),
          ]);
          const map: Record<string, { date: string; sales: number; purchases: number; expenses: number; incomes: number; profit: number }> = {};
          const ensure = (d: string) => (map[d] ||= { date: d, sales: 0, purchases: 0, expenses: 0, incomes: 0, profit: 0 });
          (s || []).forEach((r: any) => { ensure(r.sale_date).sales += Number(r.total_amount || 0); });
          (p || []).forEach((r: any) => { ensure(r.purchase_date).purchases += Number(r.total_amount || 0); });
          (e || []).forEach((r: any) => { ensure(r.expense_date).expenses += Number(r.amount || 0); });
          (i || []).forEach((r: any) => { ensure(r.income_date).incomes += Number(r.amount || 0); });
          const rows = Object.values(map).map((r) => ({ ...r, profit: r.sales + r.incomes - r.purchases - r.expenses }))
            .sort((a, b) => b.date.localeCompare(a.date));
          setReportRows(rows);
          setReportTotals({
            count: rows.length,
            total: rows.reduce((s2, r) => s2 + r.sales + r.incomes, 0),
            paid: rows.reduce((s2, r) => s2 + r.purchases + r.expenses, 0),
            due: rows.reduce((s2, r) => s2 + r.profit, 0),
          });
        }
      } finally {
        setReportLoading(false);
      }
    })();
  }, [reportTab, fromDate, toDate]);

  const exportReport = (fmt: "csv" | "xlsx" | "pdf") => {
    if (!reportRows.length) return;
    const filename = `${reportTab}-${fromDate}_to_${toDate}`;
    const title = `${reportTab.toUpperCase()} Report (${fromDate} to ${toDate})`;
    const rows = reportRows.map((r: any) => {
      if (reportTab === "sales") return {
        Invoice: r.invoice_no, Date: r.sale_date, Customer: r.customer_name,
        Mobile: r.customer_mobile, Total: Number(r.total_amount), Paid: Number(r.paid_amount),
        Due: Number(r.due_amount), Method: r.payment_method,
      };
      if (reportTab === "purchase") return {
        Invoice: r.invoice_no, Date: r.purchase_date, Supplier: r.supplier_name,
        Total: Number(r.total_amount), Paid: Number(r.paid_amount), Due: Number(r.due_amount), Method: r.payment_method,
      };
      if (reportTab === "expense") return {
        Date: r.expense_date, Category: r.category, Amount: Number(r.amount), Method: r.payment_method, Note: r.note || "",
      };
      if (reportTab === "cash_closing") return {
        Date: r.closing_date, Branch: r.branch_name, Shift: r.shift,
        Opening: Number(r.opening_cash), CashSales: Number(r.cash_sales), DueCollection: Number(r.due_collection),
        Expense: Number(r.expense_amount), SupplierPayment: Number(r.supplier_payment),
        BankDeposit: Number(r.bank_deposit), Withdraw: Number(r.withdraw_amount),
        Expected: Number(r.expected_cash), Closing: Number(r.closing_cash), Difference: Number(r.difference),
        Status: r.is_locked ? "Locked" : "Open",
      };
      return {
        Date: r.date, Sales: r.sales, Incomes: r.incomes, Purchases: r.purchases, Expenses: r.expenses, Profit: r.profit,
      };
    }) as any[];
    if (fmt === "csv") exportCSV(filename, rows);
    else if (fmt === "xlsx") exportXLSX(filename, rows);
    else exportPDF(filename, title, rows);
  };

  return (
    <PageLayout>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-foreground">{tr("reportsTitle")}</h1>
        <p className="text-sm text-muted-foreground">{tr("reportsSubtitle")}</p>
      </div>

      {/* ===== Reports Hub Cards ===== */}
      <div className="mb-8 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
        {[
          { to: "/sales", icon: Receipt, label: tr("salesReport"), color: "text-blue-600" },
          { to: "/purchases", icon: ShoppingCart, label: tr("purchaseReport"), color: "text-purple-600" },
          { to: "/products", icon: Boxes, label: tr("stockReport"), color: "text-amber-600" },
          { to: "/customers", icon: UserCheck, label: tr("customerReport"), color: "text-emerald-600" },
          { to: "/suppliers", icon: Truck, label: tr("supplierReport"), color: "text-indigo-600" },
          { to: "/expenses", icon: Receipt, label: tr("expenseReport"), color: "text-rose-600" },
          { to: "/wallet-management", icon: Wallet, label: tr("walletReport"), color: "text-cyan-600" },
          { to: "/branch-reports", icon: Building2, label: tr("branchReports"), color: "text-orange-600" },
          { to: "/godowns", icon: Warehouse, label: tr("godownReport"), color: "text-teal-600" },
          { to: "/damage-report", icon: AlertTriangle, label: tr("damageReport"), color: "text-orange-600" },
          { to: "/profit-loss", icon: TrendingUp, label: tr("profitLoss"), color: "text-green-600" },
          { to: "/daily-cash-closing", icon: Banknote, label: lang === "bn" ? "দৈনিক ক্যাশ ক্লোজিং" : "Daily Cash Closing", color: "text-pink-600" },
        ].map((c) => (
          <Link
            key={c.to}
            to={c.to}
            className="flex flex-col items-center justify-center gap-2 rounded-xl border border-border bg-card p-4 text-center transition-all hover:border-primary hover:shadow-md"
          >
            <c.icon className={`h-6 w-6 ${c.color}`} />
            <span className="text-xs font-medium text-foreground">{c.label}</span>
          </Link>
        ))}
      </div>

      {/* ===== Type-wise Report Section ===== */}
      <div className="mb-8">
        <div className="mb-4 flex items-center gap-2">
          <Layers className="h-5 w-5 text-primary" />
          <h2 className="text-lg font-bold text-foreground">{tr("typeWiseReport")}</h2>
        </div>
        <p className="mb-4 text-sm text-muted-foreground">{tr("typeWiseSubtitle")}</p>

        {loading ? (
          <div className="flex h-40 items-center justify-center text-muted-foreground">
            {lang === "bn" ? "লোড হচ্ছে..." : "Loading..."}
          </div>
        ) : (
          <>
            {/* Summary Cards */}
            <div className="mb-6 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
              {/* Overall total */}
              <div className="rounded-xl border border-border bg-card p-5">
                <div className="flex items-center gap-2 text-muted-foreground">
                  <Package className="h-4 w-4" />
                  <p className="text-sm">{tr("totalProductsLabel")}</p>
                </div>
                <p className="mt-2 text-2xl font-bold text-foreground">{totalProducts}</p>
                <p className="text-xs text-muted-foreground">
                  {typeStats.length} {lang === "bn" ? "টি ধরন" : "types"}
                </p>
              </div>

              {/* Per type cards */}
              {typeStats.map((ts) => (
                <div key={ts.id} className="rounded-xl border border-border bg-card p-5">
                  <div className="flex items-center gap-2">
                    <span
                      className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-semibold ${ts.bgClass}`}
                    >
                      {ts.icon} {lang === "bn" ? ts.name_bn || ts.name : ts.name}
                    </span>
                  </div>
                  <p className="mt-3 text-2xl font-bold text-foreground">{ts.productCount}</p>
                  <div className="mt-1 flex items-center justify-between">
                    <p className="text-xs text-muted-foreground">
                      {tr("totalStockValue")}: ৳{ts.totalStockValue.toLocaleString()}
                    </p>
                  </div>
                  <p className="mt-0.5 text-xs text-muted-foreground">
                    {tr("avgPrice")}: ৳{Math.round(ts.avgRetailPrice).toLocaleString()}
                  </p>
                </div>
              ))}
            </div>

            {/* Charts Row */}
            <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
              {/* Donut / Pie-like chart */}
              <div className="rounded-xl border border-border bg-card p-6">
                <h3 className="mb-4 text-sm font-bold text-foreground">{tr("typeDistribution")}</h3>
                <div className="flex items-center justify-center gap-8">
                  {/* Simple ring chart via SVG */}
                  <svg viewBox="0 0 100 100" className="h-40 w-40">
                    {(() => {
                      let cumulative = 0;
                      return typeStats.map((ts) => {
                        const pct = totalProducts > 0 ? ts.productCount / totalProducts : 0;
                        const startAngle = cumulative * 360;
                        cumulative += pct;
                        const endAngle = cumulative * 360;

                        const r = 38;
                        const cx = 50;
                        const cy = 50;
                        const startRad = ((startAngle - 90) * Math.PI) / 180;
                        const endRad = ((endAngle - 90) * Math.PI) / 180;
                        const x1 = cx + r * Math.cos(startRad);
                        const y1 = cy + r * Math.sin(startRad);
                        const x2 = cx + r * Math.cos(endRad);
                        const y2 = cy + r * Math.sin(endRad);
                        const largeArc = endAngle - startAngle > 180 ? 1 : 0;

                        if (pct === 0) return null;
                        if (pct >= 1) {
                          return (
                            <circle
                              key={ts.id}
                              cx={cx}
                              cy={cy}
                              r={r}
                              fill="none"
                              stroke={ts.color}
                              strokeWidth="20"
                            />
                          );
                        }

                        return (
                          <path
                            key={ts.id}
                            d={`M ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2}`}
                            fill="none"
                            stroke={ts.color}
                            strokeWidth="20"
                            strokeLinecap="butt"
                          />
                        );
                      });
                    })()}
                    <text
                      x="50"
                      y="48"
                      textAnchor="middle"
                      className="fill-foreground text-[10px] font-bold"
                    >
                      {totalProducts}
                    </text>
                    <text
                      x="50"
                      y="58"
                      textAnchor="middle"
                      className="fill-muted-foreground text-[5px]"
                    >
                      {lang === "bn" ? "মোট পণ্য" : "Total"}
                    </text>
                  </svg>

                  {/* Legend */}
                  <div className="space-y-3">
                    {typeStats.map((ts) => {
                      const pct = totalProducts > 0 ? ((ts.productCount / totalProducts) * 100).toFixed(1) : "0";
                      return (
                        <div key={ts.id} className="flex items-center gap-3">
                          <div
                            className="h-3 w-3 rounded-full"
                            style={{ backgroundColor: ts.color }}
                          />
                          <div>
                            <p className="text-sm font-medium text-foreground">
                              {ts.icon} {lang === "bn" ? ts.name_bn || ts.name : ts.name}
                            </p>
                            <p className="text-xs text-muted-foreground">
                              {ts.productCount} ({pct}%)
                            </p>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>

              {/* Bar chart - Stock Value Comparison */}
              <div className="rounded-xl border border-border bg-card p-6">
                <h3 className="mb-4 text-sm font-bold text-foreground">{tr("typeStockComparison")}</h3>
                <div className="space-y-4">
                  {typeStats.map((ts) => (
                    <div key={ts.id}>
                      <div className="mb-1.5 flex items-center justify-between">
                        <span className="flex items-center gap-2 text-sm font-medium text-foreground">
                          <span
                            className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-semibold ${ts.bgClass}`}
                          >
                            {ts.icon} {lang === "bn" ? ts.name_bn || ts.name : ts.name}
                          </span>
                        </span>
                        <span className="text-sm font-semibold text-foreground">
                          ৳{ts.totalStockValue.toLocaleString()}
                        </span>
                      </div>
                      <div className="h-6 w-full rounded-full bg-muted overflow-hidden">
                        <div
                          className="h-full rounded-full transition-all duration-700"
                          style={{
                            width: `${(ts.totalStockValue / maxValue) * 100}%`,
                            backgroundColor: ts.color,
                            minWidth: ts.totalStockValue > 0 ? "1rem" : 0,
                          }}
                        />
                      </div>
                      <div className="mt-1 flex justify-between text-xs text-muted-foreground">
                        <span>
                          {ts.productCount} {lang === "bn" ? "পণ্য" : "products"}
                        </span>
                        <span>
                          {tr("avgPrice")}: ৳{Math.round(ts.avgRetailPrice).toLocaleString()}
                        </span>
                      </div>
                    </div>
                  ))}

                  {typeStats.length === 0 && (
                    <div className="flex h-20 items-center justify-center text-muted-foreground text-sm">
                      {lang === "bn" ? "কোনো তথ্য নেই" : "No data available"}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </>
        )}
      </div>

      {/* ===== Detailed Reports: filter + tabs + export ===== */}
      <div className="rounded-xl border border-border bg-card p-6">
        <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
          <h2 className="flex items-center gap-2 text-sm font-bold text-foreground">
            <Calendar className="h-4 w-4 text-primary" />
            {lang === "bn" ? "বিস্তারিত রিপোর্ট" : "Detailed Report"}
          </h2>
          <div className="flex flex-wrap items-center gap-2">
            <input type="date" value={fromDate} onChange={(e) => setFromDate(e.target.value)}
              className="rounded-md border border-input bg-background px-2 py-1 text-xs" />
            <span className="text-xs text-muted-foreground">→</span>
            <input type="date" value={toDate} onChange={(e) => setToDate(e.target.value)}
              className="rounded-md border border-input bg-background px-2 py-1 text-xs" />
            <button onClick={() => exportReport("csv")} disabled={!reportRows.length}
              className="flex items-center gap-1 rounded-md border border-border bg-background px-2.5 py-1 text-xs font-medium hover:bg-muted disabled:opacity-50">
              <Download className="h-3.5 w-3.5" />CSV
            </button>
            <button onClick={() => exportReport("xlsx")} disabled={!reportRows.length}
              className="flex items-center gap-1 rounded-md border border-emerald-500/40 bg-emerald-500/10 px-2.5 py-1 text-xs font-medium text-emerald-700 hover:bg-emerald-500/20 dark:text-emerald-400 disabled:opacity-50">
              <FileSpreadsheet className="h-3.5 w-3.5" />Excel
            </button>
            <button onClick={() => exportReport("pdf")} disabled={!reportRows.length}
              className="flex items-center gap-1 rounded-md border border-rose-500/40 bg-rose-500/10 px-2.5 py-1 text-xs font-medium text-rose-700 hover:bg-rose-500/20 dark:text-rose-400 disabled:opacity-50">
              <FileText className="h-3.5 w-3.5" />PDF
            </button>
          </div>
        </div>

        <div className="mb-4 flex flex-wrap gap-1 border-b border-border">
          {([
            { v: "sales", bn: "বিক্রয়", en: "Sales" },
            { v: "purchase", bn: "ক্রয়", en: "Purchase" },
            { v: "expense", bn: "খরচ", en: "Expense" },
            { v: "pnl", bn: "লাভ/ক্ষতি", en: "P&L" },
            { v: "cash_closing", bn: "ক্যাশ ক্লোজিং", en: "Cash Closing" },
          ] as const).map((t) => (
            <button key={t.v} onClick={() => setReportTab(t.v)}
              className={`px-3 py-1.5 text-xs font-medium transition-colors ${reportTab === t.v ? "border-b-2 border-primary text-primary" : "text-muted-foreground hover:text-foreground"}`}>
              {lang === "bn" ? t.bn : t.en}
            </button>
          ))}
        </div>

        <div className="mb-4 grid grid-cols-2 gap-2 sm:grid-cols-4">
          <div className="rounded-lg bg-muted/40 p-2.5">
            <p className="text-[10px] uppercase text-muted-foreground">{lang === "bn" ? "এন্ট্রি" : "Entries"}</p>
            <p className="text-sm font-bold text-foreground">{reportTotals.count}</p>
          </div>
          <div className="rounded-lg bg-blue-500/10 p-2.5">
            <p className="text-[10px] uppercase text-muted-foreground">{reportTab === "pnl" ? (lang === "bn" ? "আয়" : "Income") : (lang === "bn" ? "মোট" : "Total")}</p>
            <p className="text-sm font-bold text-blue-700 dark:text-blue-400">৳{reportTotals.total.toLocaleString()}</p>
          </div>
          {reportTab !== "expense" && (
            <div className="rounded-lg bg-emerald-500/10 p-2.5">
              <p className="text-[10px] uppercase text-muted-foreground">{reportTab === "pnl" ? (lang === "bn" ? "ব্যয়" : "Outflow") : (lang === "bn" ? "পরিশোধিত" : "Paid")}</p>
              <p className="text-sm font-bold text-emerald-700 dark:text-emerald-400">৳{reportTotals.paid.toLocaleString()}</p>
            </div>
          )}
          {reportTab !== "expense" && (
            <div className={`rounded-lg p-2.5 ${reportTab === "pnl" ? (reportTotals.due >= 0 ? "bg-emerald-500/10" : "bg-rose-500/10") : "bg-rose-500/10"}`}>
              <p className="text-[10px] uppercase text-muted-foreground">{reportTab === "pnl" ? (lang === "bn" ? "নেট লাভ" : "Net Profit") : (lang === "bn" ? "বাকি" : "Due")}</p>
              <p className={`text-sm font-bold ${reportTab === "pnl" && reportTotals.due < 0 ? "text-rose-700 dark:text-rose-400" : "text-emerald-700 dark:text-emerald-400"}`}>৳{reportTotals.due.toLocaleString()}</p>
            </div>
          )}
        </div>

        <div className="overflow-x-auto rounded-lg border border-border">
          {reportLoading ? (
            <div className="p-8 text-center text-sm text-muted-foreground">{lang === "bn" ? "লোড হচ্ছে..." : "Loading..."}</div>
          ) : reportRows.length === 0 ? (
            <div className="p-8 text-center text-sm text-muted-foreground">{lang === "bn" ? "কোনো ডেটা নেই" : "No data"}</div>
          ) : (
            <table className="w-full text-xs">
              <thead className="bg-muted/40">
                <tr className="text-left">
                  {reportTab === "sales" && ["#", "Invoice", "Date", "Customer", "Total", "Paid", "Due"].map((h) => <th key={h} className="px-3 py-2 font-semibold">{h}</th>)}
                  {reportTab === "purchase" && ["#", "Invoice", "Date", "Supplier", "Total", "Paid", "Due"].map((h) => <th key={h} className="px-3 py-2 font-semibold">{h}</th>)}
                  {reportTab === "expense" && ["#", "Date", "Category", "Amount", "Method", "Note"].map((h) => <th key={h} className="px-3 py-2 font-semibold">{h}</th>)}
                  {reportTab === "pnl" && ["Date", "Sales", "Income", "Purchases", "Expenses", "Profit"].map((h) => <th key={h} className="px-3 py-2 font-semibold">{h}</th>)}
                  {reportTab === "cash_closing" && ["Date", "Branch", "Shift", "Opening", "Cash Sales", "Due Coll.", "Expense", "Supplier", "Bank", "Cash Out", "Expected", "Closing", "Diff", "Status"].map((h) => <th key={h} className="px-3 py-2 font-semibold whitespace-nowrap">{h}</th>)}
                </tr>
              </thead>
              <tbody>
                {reportRows.slice(0, 100).map((r: any, i: number) => (
                  <tr key={i} className="border-t border-border">
                    {reportTab === "sales" && (<>
                      <td className="px-3 py-1.5">{i + 1}</td>
                      <td className="px-3 py-1.5 font-mono">{r.invoice_no}</td>
                      <td className="px-3 py-1.5">{r.sale_date}</td>
                      <td className="px-3 py-1.5">{r.customer_name}</td>
                      <td className="px-3 py-1.5 text-right">৳{Number(r.total_amount).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right text-emerald-600">৳{Number(r.paid_amount).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right text-rose-600">৳{Number(r.due_amount).toLocaleString()}</td>
                    </>)}
                    {reportTab === "purchase" && (<>
                      <td className="px-3 py-1.5">{i + 1}</td>
                      <td className="px-3 py-1.5 font-mono">{r.invoice_no}</td>
                      <td className="px-3 py-1.5">{r.purchase_date}</td>
                      <td className="px-3 py-1.5">{r.supplier_name}</td>
                      <td className="px-3 py-1.5 text-right">৳{Number(r.total_amount).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right text-emerald-600">৳{Number(r.paid_amount).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right text-rose-600">৳{Number(r.due_amount).toLocaleString()}</td>
                    </>)}
                    {reportTab === "expense" && (<>
                      <td className="px-3 py-1.5">{i + 1}</td>
                      <td className="px-3 py-1.5">{r.expense_date}</td>
                      <td className="px-3 py-1.5">{r.category}</td>
                      <td className="px-3 py-1.5 text-right text-rose-600">৳{Number(r.amount).toLocaleString()}</td>
                      <td className="px-3 py-1.5">{r.payment_method}</td>
                      <td className="px-3 py-1.5 text-muted-foreground">{r.note}</td>
                    </>)}
                    {reportTab === "pnl" && (<>
                      <td className="px-3 py-1.5">{r.date}</td>
                      <td className="px-3 py-1.5 text-right">৳{r.sales.toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right">৳{r.incomes.toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right">৳{r.purchases.toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right">৳{r.expenses.toLocaleString()}</td>
                      <td className={`px-3 py-1.5 text-right font-bold ${r.profit >= 0 ? "text-emerald-600" : "text-rose-600"}`}>৳{r.profit.toLocaleString()}</td>
                    </>)}
                    {reportTab === "cash_closing" && (<>
                      <td className="px-3 py-1.5 whitespace-nowrap">{r.closing_date}</td>
                      <td className="px-3 py-1.5">{r.branch_name}</td>
                      <td className="px-3 py-1.5 capitalize">{String(r.shift).replace("_"," ")}</td>
                      <td className="px-3 py-1.5 text-right">৳{Number(r.opening_cash).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right">৳{Number(r.cash_sales).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right">৳{Number(r.due_collection).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right text-rose-600">৳{Number(r.expense_amount).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right text-rose-600">৳{Number(r.supplier_payment).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right">৳{Number(r.bank_deposit).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right">৳{Number(r.withdraw_amount).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right">৳{Number(r.expected_cash).toLocaleString()}</td>
                      <td className="px-3 py-1.5 text-right font-semibold">৳{Number(r.closing_cash).toLocaleString()}</td>
                      <td className={`px-3 py-1.5 text-right font-bold ${Number(r.difference) === 0 ? "text-muted-foreground" : Number(r.difference) > 0 ? "text-emerald-600" : "text-rose-600"}`}>৳{Number(r.difference).toLocaleString()}</td>
                      <td className="px-3 py-1.5"><span className={`rounded px-1.5 py-0.5 text-[10px] font-semibold ${r.is_locked ? "bg-rose-500/10 text-rose-700" : "bg-emerald-500/10 text-emerald-700"}`}>{r.is_locked ? "Locked" : "Open"}</span></td>
                    </>)}
                  </tr>
                ))}
              </tbody>
            </table>
          )}
          {reportRows.length > 100 && (
            <div className="border-t border-border p-2 text-center text-[11px] text-muted-foreground">
              {lang === "bn" ? `প্রথম ১০০ দেখানো হচ্ছে · মোট ${reportRows.length} · এক্সপোর্টে সব আসবে` : `Showing first 100 of ${reportRows.length} · export contains all`}
            </div>
          )}
        </div>
      </div>
    </PageLayout>
  );
}
