import { createFileRoute } from "@tanstack/react-router";
import { PageLayout } from "@/components/PageLayout";
import { useEffect, useMemo, useState, useCallback } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useLanguage } from "@/hooks/use-language";
import { usePermissions } from "@/hooks/use-permissions";
import { useAuth } from "@/hooks/use-auth";
import { Plus, Lock, Unlock, Printer, FileDown, Trash2, Wallet, TrendingUp, TrendingDown, AlertTriangle, X, FileSpreadsheet, FileText } from "lucide-react";
import { toast } from "sonner";
import { exportXLSX, exportPDF, type ExportRow } from "@/lib/export-utils";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";

export const Route = createFileRoute("/_authenticated/daily-cash-closing")({
  head: () => ({ meta: [{ title: "Daily Cash Closing — Niyamah ERP" }] }),
  component: DailyCashClosingPage,
});

type Branch = { id: string; name: string };
type Cashier = { id: string; full_name: string | null };
type Closing = {
  id: string;
  branch_id: string | null;
  cashier_id: string | null;
  shift: string;
  closing_date: string;
  opening_cash: number;
  total_sales: number;
  cash_sales: number;
  due_collection: number;
  expense_amount: number;
  supplier_payment: number;
  bank_deposit: number;
  withdraw_amount: number;
  closing_cash: number;
  expected_cash: number;
  difference: number;
  note: string;
  is_locked: boolean;
  closed_by: string | null;
  closed_at: string | null;
};

const SHIFTS = [
  { value: "full_day", label_en: "Full Day", label_bn: "পূর্ণ দিন" },
  { value: "morning", label_en: "Morning", label_bn: "সকাল" },
  { value: "afternoon", label_en: "Afternoon", label_bn: "দুপুর" },
  { value: "evening", label_en: "Evening", label_bn: "সন্ধ্যা" },
  { value: "night", label_en: "Night", label_bn: "রাত" },
];

const today = () => new Date().toISOString().slice(0, 10);

const emptyForm = {
  branch_id: "",
  cashier_id: "",
  shift: "full_day",
  closing_date: today(),
  opening_cash: 0,
  cash_sales: 0,
  due_collection: 0,
  expense_amount: 0,
  supplier_payment: 0,
  bank_deposit: 0,
  withdraw_amount: 0,
  closing_cash: 0,
  note: "",
};

function DailyCashClosingPage() {
  const { lang } = useLanguage();
  const isBn = lang === "bn";
  const { isAdmin } = usePermissions();
  const { user } = useAuth();

  const [branches, setBranches] = useState<Branch[]>([]);
  const [cashiers, setCashiers] = useState<Cashier[]>([]);
  const [rows, setRows] = useState<Closing[]>([]);
  const [filterBranch, setFilterBranch] = useState<string>("all");
  const [filterCashier, setFilterCashier] = useState<string>("all");
  const [filterShift, setFilterShift] = useState<string>("all");
  const [filterFrom, setFilterFrom] = useState<string>("");
  const [filterTo, setFilterTo] = useState<string>("");
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({ ...emptyForm });
  const [saving, setSaving] = useState(false);
  const [autoCalc, setAutoCalc] = useState(true);

  const fetchData = useCallback(async () => {
    setLoading(true);
    let q = supabase
      .from("daily_cash_closings")
      .select("*")
      .order("closing_date", { ascending: false })
      .limit(500);
    if (filterBranch !== "all") q = q.eq("branch_id", filterBranch);
    if (filterCashier !== "all") q = q.eq("cashier_id", filterCashier);
    if (filterShift !== "all") q = q.eq("shift", filterShift);
    if (filterFrom) q = q.gte("closing_date", filterFrom);
    if (filterTo) q = q.lte("closing_date", filterTo);
    const [{ data }, { data: br }, { data: cs }] = await Promise.all([
      q,
      supabase.from("branches").select("id, name").is("deleted_at", null),
      supabase.from("profiles").select("id, full_name").eq("status", "active"),
    ]);
    setRows((data as Closing[]) || []);
    setBranches((br as Branch[]) || []);
    setCashiers((cs as Cashier[]) || []);
    setLoading(false);
  }, [filterBranch, filterCashier, filterShift, filterFrom, filterTo]);

  useEffect(() => { fetchData(); }, [fetchData]);

  const loadAutoFigures = useCallback(async () => {
    if (!form.closing_date) return;
    const dayStart = `${form.closing_date}T00:00:00`;
    const dayEnd = `${form.closing_date}T23:59:59`;

    let salesQ = supabase
      .from("sales")
      .select("paid_amount, total_amount, payment_method, branch_id, sale_date, created_by")
      .eq("sale_date", form.closing_date);
    if (form.branch_id) salesQ = salesQ.eq("branch_id", form.branch_id);
    if (form.cashier_id) salesQ = salesQ.eq("created_by", form.cashier_id);
    const { data: sales } = await salesQ;

    const cashSales = (sales || [])
      .filter((s: any) => (s.payment_method || "cash") === "cash")
      .reduce((sum: number, s: any) => sum + Number(s.paid_amount || 0), 0);
    const totalSales = (sales || []).reduce((sum: number, s: any) => sum + Number(s.total_amount || 0), 0);

    let txQ = supabase
      .from("customer_transactions")
      .select("amount, type, method, branch_id, created_at")
      .gte("created_at", dayStart)
      .lte("created_at", dayEnd);
    if (form.branch_id) txQ = txQ.eq("branch_id", form.branch_id);
    const { data: tx } = await txQ;
    const dueCollection = (tx || [])
      .filter((t: any) => ["collection", "due_collection", "payment", "received"].includes(t.type) && (t.method || "cash") === "cash")
      .reduce((sum: number, t: any) => sum + Number(t.amount || 0), 0);

    let expQ = supabase
      .from("expenses")
      .select("amount, payment_method, branch_id, expense_date")
      .eq("expense_date", form.closing_date);
    if (form.branch_id) expQ = expQ.eq("branch_id", form.branch_id);
    const { data: exp } = await expQ;
    const expenseAmount = (exp || [])
      .filter((e: any) => (e.payment_method || "cash") === "cash")
      .reduce((sum: number, e: any) => sum + Number(e.amount || 0), 0);

    // Supplier payments (purchases paid_amount in cash for the day)
    let purQ = supabase
      .from("purchases")
      .select("paid_amount, payment_method, purchase_date")
      .eq("purchase_date", form.closing_date);
    const { data: pur } = await purQ;
    const supplierPayment = (pur || [])
      .filter((p: any) => (p.payment_method || "cash") === "cash")
      .reduce((sum: number, p: any) => sum + Number(p.paid_amount || 0), 0);

    // Auto opening carry-forward: previous closing for same branch + cashier + shift
    let prevQ = supabase
      .from("daily_cash_closings")
      .select("closing_cash, closing_date")
      .lt("closing_date", form.closing_date)
      .eq("shift", form.shift || "full_day")
      .order("closing_date", { ascending: false })
      .limit(1);
    prevQ = form.branch_id ? prevQ.eq("branch_id", form.branch_id) : prevQ.is("branch_id", null);
    prevQ = form.cashier_id ? prevQ.eq("cashier_id", form.cashier_id) : prevQ.is("cashier_id", null);
    const { data: prev } = await prevQ;
    const carryOpening = prev && prev[0] ? Number((prev[0] as any).closing_cash || 0) : 0;

    setForm((f) => ({
      ...f,
      opening_cash: f.opening_cash ? f.opening_cash : carryOpening,
      cash_sales: cashSales,
      due_collection: dueCollection,
      expense_amount: expenseAmount,
      supplier_payment: f.supplier_payment ? f.supplier_payment : supplierPayment,
    }));
    (window as any).__totalSalesForClosing = totalSales;
  }, [form.closing_date, form.branch_id, form.cashier_id, form.shift]);

  useEffect(() => {
    if (open && autoCalc) loadAutoFigures();
  }, [open, autoCalc, loadAutoFigures]);

  const expectedCash = useMemo(() => {
    const o = Number(form.opening_cash || 0);
    const cs = Number(form.cash_sales || 0);
    const dc = Number(form.due_collection || 0);
    const ex = Number(form.expense_amount || 0);
    const sp = Number(form.supplier_payment || 0);
    const bd = Number(form.bank_deposit || 0);
    const w = Number(form.withdraw_amount || 0);
    return o + cs + dc - ex - sp - bd - w;
  }, [form]);

  const difference = useMemo(
    () => Number(form.closing_cash || 0) - expectedCash,
    [form.closing_cash, expectedCash]
  );

  const summary = useMemo(() => {
    const totalClosing = rows.reduce((s, r) => s + Number(r.closing_cash || 0), 0);
    const totalCashIn = rows.reduce((s, r) => s + Number(r.cash_sales || 0) + Number(r.due_collection || 0), 0);
    const totalCashOut = rows.reduce((s, r) => s + Number(r.expense_amount || 0) + Number(r.supplier_payment || 0) + Number(r.bank_deposit || 0) + Number(r.withdraw_amount || 0), 0);
    const mismatches = rows.filter((r) => Math.abs(Number(r.difference || 0)) > 0.01).length;
    return { totalClosing, totalCashIn, totalCashOut, mismatches };
  }, [rows]);

  const openAdd = () => {
    setForm({
      ...emptyForm,
      branch_id: filterBranch !== "all" ? filterBranch : "",
      cashier_id: filterCashier !== "all" ? filterCashier : (user?.id || ""),
      shift: filterShift !== "all" ? filterShift : "full_day",
    });
    setAutoCalc(true);
    setOpen(true);
  };

  const save = async (lockNow: boolean) => {
    if (!form.closing_date) { toast.error(isBn ? "তারিখ দিন" : "Date required"); return; }
    setSaving(true);
    const totalSales = (window as any).__totalSalesForClosing || 0;
    const payload = {
      branch_id: form.branch_id || null,
      cashier_id: form.cashier_id || null,
      shift: form.shift || "full_day",
      closing_date: form.closing_date,
      opening_cash: Number(form.opening_cash || 0),
      total_sales: Number(totalSales),
      cash_sales: Number(form.cash_sales || 0),
      due_collection: Number(form.due_collection || 0),
      expense_amount: Number(form.expense_amount || 0),
      supplier_payment: Number(form.supplier_payment || 0),
      bank_deposit: Number(form.bank_deposit || 0),
      withdraw_amount: Number(form.withdraw_amount || 0),
      closing_cash: Number(form.closing_cash || 0),
      expected_cash: expectedCash,
      difference,
      note: form.note,
      is_locked: lockNow,
      closed_by: user?.id || null,
      closed_at: lockNow ? new Date().toISOString() : null,
    };
    // Manual upsert keyed on (date, branch, cashier, shift)
    let exQ = supabase
      .from("daily_cash_closings")
      .select("id, is_locked")
      .eq("closing_date", payload.closing_date)
      .eq("shift", payload.shift);
    exQ = payload.branch_id ? exQ.eq("branch_id", payload.branch_id) : exQ.is("branch_id", null);
    exQ = payload.cashier_id ? exQ.eq("cashier_id", payload.cashier_id) : exQ.is("cashier_id", null);
    const { data: existing } = await exQ.maybeSingle();

    let error: any = null;
    if (existing?.id) {
      if (existing.is_locked && !isAdmin) {
        setSaving(false);
        toast.error(isBn ? "এই ক্লোজিং লকড — অ্যাডমিন লাগবে" : "Closing locked — admin only");
        return;
      }
      ({ error } = await supabase.from("daily_cash_closings").update(payload).eq("id", existing.id));
    } else {
      ({ error } = await supabase.from("daily_cash_closings").insert(payload));
    }
    setSaving(false);
    if (error) { toast.error(error.message); return; }
    toast.success(lockNow ? (isBn ? "ক্লোজ ও লক হয়েছে" : "Closed & locked") : (isBn ? "সংরক্ষিত হয়েছে" : "Saved"));
    setOpen(false);
    fetchData();
  };

  const toggleLock = async (r: Closing) => {
    if (r.is_locked && !isAdmin) { toast.error(isBn ? "শুধু অ্যাডমিন আনলক করতে পারবেন" : "Admin only"); return; }
    const patch: any = r.is_locked
      ? { is_locked: false, reopened_by: user?.id, reopened_at: new Date().toISOString() }
      : { is_locked: true, closed_by: user?.id, closed_at: new Date().toISOString() };
    const { error } = await supabase.from("daily_cash_closings").update(patch).eq("id", r.id);
    if (error) { toast.error(error.message); return; }
    toast.success(r.is_locked ? (isBn ? "আনলক হয়েছে" : "Reopened") : (isBn ? "লক হয়েছে" : "Locked"));
    fetchData();
  };

  const del = async (r: Closing) => {
    if (!isAdmin) return;
    if (!confirm(isBn ? "মুছবেন?" : "Delete?")) return;
    const { error } = await supabase.from("daily_cash_closings").delete().eq("id", r.id);
    if (error) { toast.error(error.message); return; }
    toast.success(isBn ? "মুছে ফেলা হয়েছে" : "Deleted");
    fetchData();
  };

  const downloadClosingReport = (r: Closing) => {
    const branchNm = branches.find((b) => b.id === r.branch_id)?.name || (isBn ? "প্রধান" : "Main");
    const cashierNm = cashiers.find((c) => c.id === r.cashier_id)?.full_name || "—";
    const shiftLbl = SHIFTS.find((s) => s.value === r.shift)?.label_en || r.shift;

    const doc = new jsPDF({ unit: "pt", format: "a4" });
    const pageW = doc.internal.pageSize.getWidth();
    const pageH = doc.internal.pageSize.getHeight();

    // Header
    doc.setFontSize(16); doc.setFont("helvetica", "bold");
    doc.text("DAILY CASH CLOSING REPORT", pageW / 2, 50, { align: "center" });
    doc.setFontSize(10); doc.setFont("helvetica", "normal");
    doc.text("Niyamah ERP — Electric & Hardware", pageW / 2, 68, { align: "center" });
    doc.setLineWidth(0.5);
    doc.line(40, 80, pageW - 40, 80);

    // Meta
    doc.setFontSize(10);
    const metaY = 100;
    doc.text(`Date:    ${r.closing_date}`, 50, metaY);
    doc.text(`Branch:  ${branchNm}`, 300, metaY);
    doc.text(`Cashier: ${cashierNm}`, 50, metaY + 16);
    doc.text(`Shift:   ${shiftLbl}`, 300, metaY + 16);
    doc.text(`Status:  ${r.is_locked ? "LOCKED" : "OPEN"}`, 50, metaY + 32);
    doc.text(`Closed:  ${r.closed_at ? new Date(r.closed_at).toLocaleString() : "—"}`, 300, metaY + 32);

    // Breakdown table
    const fmt = (n: number) => Number(n || 0).toFixed(2);
    autoTable(doc, {
      startY: metaY + 56,
      head: [["Particulars", "Amount (BDT)"]],
      body: [
        ["Opening Cash", fmt(r.opening_cash)],
        ["(+) Cash Sales", fmt(r.cash_sales)],
        ["(+) Due Collection", fmt(r.due_collection)],
        ["(-) Expense", fmt(r.expense_amount)],
        ["(-) Supplier Payment", fmt(r.supplier_payment)],
        ["(-) Bank Deposit", fmt(r.bank_deposit)],
        ["(-) Cash Out", fmt(r.withdraw_amount)],
        [{ content: "Expected Cash", styles: { fontStyle: "bold" } }, { content: fmt(r.expected_cash), styles: { fontStyle: "bold" } }],
        [{ content: "Actual Closing Cash", styles: { fontStyle: "bold" } }, { content: fmt(r.closing_cash), styles: { fontStyle: "bold" } }],
        [
          { content: "Difference (Actual − Expected)", styles: { fontStyle: "bold" } },
          { content: fmt(r.difference), styles: { fontStyle: "bold", textColor: Math.abs(Number(r.difference)) < 0.01 ? [0,0,0] : Number(r.difference) < 0 ? [200,30,30] : [200,120,0] } },
        ],
      ],
      styles: { fontSize: 10, cellPadding: 6 },
      headStyles: { fillColor: [37, 99, 235], halign: "left" },
      columnStyles: { 0: { cellWidth: 320 }, 1: { halign: "right", cellWidth: 180 } },
      margin: { left: 50, right: 50 },
    });

    // Note
    let y = (doc as any).lastAutoTable?.finalY ? (doc as any).lastAutoTable.finalY + 20 : metaY + 300;
    if (r.note) {
      doc.setFont("helvetica", "bold"); doc.text("Note:", 50, y);
      doc.setFont("helvetica", "normal");
      const noteLines = doc.splitTextToSize(r.note, pageW - 100);
      doc.text(noteLines, 50, y + 14);
      y += 14 + noteLines.length * 12 + 10;
    }

    // Signature lines
    const sigY = Math.max(y + 60, pageH - 140);
    doc.setLineWidth(0.5);
    doc.line(70, sigY, 240, sigY);
    doc.line(pageW - 240, sigY, pageW - 70, sigY);
    doc.setFontSize(10);
    doc.text("Cashier Signature", 155, sigY + 14, { align: "center" });
    doc.text(cashierNm, 155, sigY + 28, { align: "center" });
    doc.text("Manager / Authorized Signature", pageW - 155, sigY + 14, { align: "center" });

    // Footer
    doc.setFontSize(8); doc.setTextColor(120);
    doc.text(`Generated: ${new Date().toLocaleString()}`, pageW / 2, pageH - 30, { align: "center" });

    doc.save(`closing-report-${r.closing_date}-${branchNm.replace(/\s+/g, "_")}-${shiftLbl}.pdf`);
  };

  const exportCsv = () => {
    const header = ["Date","Branch","Opening","CashSales","DueCollection","Expense","Supplier","BankDeposit","Withdraw","Closing","Expected","Difference","Locked"];
    const branchName = (id: string | null) => branches.find((b) => b.id === id)?.name || "";
    const lines = [header.join(",")].concat(
      rows.map((r) => [
        r.closing_date,
        `"${branchName(r.branch_id)}"`,
        r.opening_cash, r.cash_sales, r.due_collection, r.expense_amount,
        r.supplier_payment, r.bank_deposit, r.withdraw_amount,
        r.closing_cash, r.expected_cash, r.difference,
        r.is_locked ? "Yes" : "No",
      ].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 = `daily-cash-closing-${today()}.csv`; a.click();
    URL.revokeObjectURL(url);
  };

  const buildExportRows = (): ExportRow[] => {
    const branchNm = (id: string | null) => branches.find((b) => b.id === id)?.name || "All";
    return rows.map((r) => ({
      Date: r.closing_date,
      Branch: branchNm(r.branch_id),
      Opening: Number(r.opening_cash).toFixed(2),
      "Cash Sales": Number(r.cash_sales).toFixed(2),
      "Due Coll.": Number(r.due_collection).toFixed(2),
      Expense: Number(r.expense_amount).toFixed(2),
      Supplier: Number(r.supplier_payment).toFixed(2),
      Bank: Number(r.bank_deposit).toFixed(2),
      Withdraw: Number(r.withdraw_amount).toFixed(2),
      Closing: Number(r.closing_cash).toFixed(2),
      Expected: Number(r.expected_cash).toFixed(2),
      Difference: Number(r.difference).toFixed(2),
      Locked: r.is_locked ? "Yes" : "No",
    }));
  };

  const exportXlsx = async () => {
    const data = buildExportRows();
    if (!data.length) { toast.error(isBn ? "ডেটা নেই" : "No data"); return; }
    await exportXLSX(`daily-cash-closing-${today()}`, data, "Daily Cash Closing");
  };

  const exportPdf = () => {
    const data = buildExportRows();
    if (!data.length) { toast.error(isBn ? "ডেটা নেই" : "No data"); return; }
  };

  const branchName = (id: string | null) => branches.find((b) => b.id === id)?.name || (isBn ? "সকল শাখা" : "All branches");


  return (
    <PageLayout>
      <div className="space-y-6 p-4 md:p-6">
        <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
          <div>
            <h1 className="text-2xl font-bold text-foreground">
              {isBn ? "দৈনিক ক্যাশ ক্লোজিং" : "Daily Cash Closing"}
            </h1>
            <p className="text-sm text-muted-foreground">
              {isBn ? "প্রতিদিনের নগদ আয়, ব্যয় ও ক্লোজিং ব্যালেন্স ম্যানেজ করুন" : "Manage daily cash inflows, outflows and closing balance"}
            </p>
          </div>
          <div className="flex gap-2">
            <button onClick={exportCsv} className="flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-2 text-sm hover:bg-muted/40">
              <FileDown className="h-4 w-4" /> CSV
            </button>
            <button onClick={exportXlsx} className="flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-2 text-sm hover:bg-muted/40">
              <FileSpreadsheet className="h-4 w-4" /> Excel
            </button>
            <button onClick={exportPdf} className="flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-2 text-sm hover:bg-muted/40">
              <FileText className="h-4 w-4" /> PDF
            </button>
            <button onClick={() => window.print()} className="flex items-center gap-1.5 rounded-lg border border-border bg-card px-3 py-2 text-sm hover:bg-muted/40">
              <Printer className="h-4 w-4" /> {isBn ? "প্রিন্ট" : "Print"}
            </button>
            <button onClick={openAdd} className="flex items-center gap-1.5 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90">
              <Plus className="h-4 w-4" /> {isBn ? "নতুন ক্লোজিং" : "New Closing"}
            </button>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <SummaryCard icon={<Wallet className="h-5 w-5" />} label={isBn ? "মোট ক্লোজিং ক্যাশ" : "Total Closing Cash"} value={summary.totalClosing} tone="primary" />
          <SummaryCard icon={<TrendingUp className="h-5 w-5" />} label={isBn ? "ক্যাশ ইন" : "Cash In"} value={summary.totalCashIn} tone="success" />
          <SummaryCard icon={<TrendingDown className="h-5 w-5" />} label={isBn ? "ক্যাশ আউট" : "Cash Out"} value={summary.totalCashOut} tone="warning" />
          <SummaryCard icon={<AlertTriangle className="h-5 w-5" />} label={isBn ? "মিসম্যাচ" : "Mismatches"} value={summary.mismatches} tone="danger" isCount />
        </div>

        <div className="flex flex-wrap gap-3 rounded-xl border border-border bg-card p-3">
          <select value={filterBranch} onChange={(e) => setFilterBranch(e.target.value)} className="rounded-lg border border-border bg-background px-3 py-2 text-sm">
            <option value="all">{isBn ? "সকল শাখা" : "All Branches"}</option>
            {branches.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
          </select>
          <select value={filterCashier} onChange={(e) => setFilterCashier(e.target.value)} className="rounded-lg border border-border bg-background px-3 py-2 text-sm">
            <option value="all">{isBn ? "সকল ক্যাশিয়ার" : "All Cashiers"}</option>
            {cashiers.map((c) => <option key={c.id} value={c.id}>{c.full_name || "—"}</option>)}
          </select>
          <select value={filterShift} onChange={(e) => setFilterShift(e.target.value)} className="rounded-lg border border-border bg-background px-3 py-2 text-sm">
            <option value="all">{isBn ? "সকল শিফট" : "All Shifts"}</option>
            {SHIFTS.map((s) => <option key={s.value} value={s.value}>{isBn ? s.label_bn : s.label_en}</option>)}
          </select>
          <input type="date" value={filterFrom} onChange={(e) => setFilterFrom(e.target.value)} className="rounded-lg border border-border bg-background px-3 py-2 text-sm" />
          <input type="date" value={filterTo} onChange={(e) => setFilterTo(e.target.value)} className="rounded-lg border border-border bg-background px-3 py-2 text-sm" />
          <button onClick={() => { setFilterBranch("all"); setFilterCashier("all"); setFilterShift("all"); setFilterFrom(""); setFilterTo(""); }} className="rounded-lg border border-border bg-background px-3 py-2 text-sm">
            {isBn ? "রিসেট" : "Reset"}
          </button>
        </div>

        <div className="overflow-x-auto rounded-xl border border-border bg-card">
          <table className="w-full text-sm">
            <thead className="bg-muted/40 text-xs uppercase text-muted-foreground">
              <tr>
                <th className="px-3 py-2 text-left">{isBn ? "তারিখ" : "Date"}</th>
                <th className="px-3 py-2 text-left">{isBn ? "শাখা" : "Branch"}</th>
                <th className="px-3 py-2 text-left">{isBn ? "ক্যাশিয়ার" : "Cashier"}</th>
                <th className="px-3 py-2 text-left">{isBn ? "শিফট" : "Shift"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "ওপেনিং" : "Opening"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "ক্যাশ সেল" : "Cash Sales"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "ডিউ কালেকশন" : "Due Coll."}</th>
                <th className="px-3 py-2 text-right">{isBn ? "খরচ" : "Expense"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "সাপ্লায়ার" : "Supplier"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "ব্যাংক" : "Bank"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "ক্যাশ আউট" : "Cash Out"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "ক্লোজিং" : "Closing"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "পার্থক্য" : "Diff"}</th>
                <th className="px-3 py-2 text-center">{isBn ? "স্ট্যাটাস" : "Status"}</th>
                <th className="px-3 py-2 text-right">{isBn ? "অ্যাকশন" : "Actions"}</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={15} className="p-6 text-center text-muted-foreground">{isBn ? "লোড হচ্ছে..." : "Loading..."}</td></tr>
              ) : rows.length === 0 ? (
                <tr><td colSpan={15} className="p-6 text-center text-muted-foreground">{isBn ? "কোনো ক্লোজিং নেই" : "No closings yet"}</td></tr>
              ) : rows.map((r) => {
                const diff = Number(r.difference || 0);
                const diffTone = Math.abs(diff) < 0.01 ? "text-muted-foreground" : diff < 0 ? "text-destructive" : "text-amber-600";
                const closingTone = Number(r.closing_cash) < 0 ? "text-destructive font-semibold" : "";
                const cashier = cashiers.find((c) => c.id === r.cashier_id)?.full_name || "—";
                const shiftLabel = SHIFTS.find((s) => s.value === r.shift)?.[isBn ? "label_bn" : "label_en"] || r.shift;
                return (
                  <tr key={r.id} className="border-t border-border">
                    <td className="px-3 py-2">{r.closing_date}</td>
                    <td className="px-3 py-2">{branchName(r.branch_id)}</td>
                    <td className="px-3 py-2">{cashier}</td>
                    <td className="px-3 py-2">{shiftLabel}</td>
                    <td className="px-3 py-2 text-right">{Number(r.opening_cash).toFixed(2)}</td>
                    <td className="px-3 py-2 text-right">{Number(r.cash_sales).toFixed(2)}</td>
                    <td className="px-3 py-2 text-right">{Number(r.due_collection).toFixed(2)}</td>
                    <td className="px-3 py-2 text-right">{Number(r.expense_amount).toFixed(2)}</td>
                    <td className="px-3 py-2 text-right">{Number(r.supplier_payment).toFixed(2)}</td>
                    <td className="px-3 py-2 text-right">{Number(r.bank_deposit).toFixed(2)}</td>
                    <td className="px-3 py-2 text-right">{Number(r.withdraw_amount).toFixed(2)}</td>
                    <td className={`px-3 py-2 text-right ${closingTone}`}>{Number(r.closing_cash).toFixed(2)}</td>
                    <td className={`px-3 py-2 text-right ${diffTone}`}>{diff.toFixed(2)}</td>
                    <td className="px-3 py-2 text-center">
                      {r.is_locked ? (
                        <span className="inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2 py-0.5 text-xs text-emerald-600">
                          <Lock className="h-3 w-3" /> {isBn ? "লকড" : "Locked"}
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 rounded-full bg-amber-500/10 px-2 py-0.5 text-xs text-amber-600">
                          <Unlock className="h-3 w-3" /> {isBn ? "খোলা" : "Open"}
                        </span>
                      )}
                    </td>
                    <td className="px-3 py-2 text-right">
                      <div className="flex justify-end gap-1">
                        <button onClick={() => downloadClosingReport(r)} className="rounded-md p-1.5 text-primary hover:bg-primary/10" title={isBn ? "ক্লোজিং রিপোর্ট PDF" : "Closing Report PDF"}>
                          <FileText className="h-4 w-4" />
                        </button>
                        <button onClick={() => toggleLock(r)} className="rounded-md p-1.5 hover:bg-muted" title={r.is_locked ? "Unlock" : "Lock"}>
                          {r.is_locked ? <Unlock className="h-4 w-4" /> : <Lock className="h-4 w-4" />}
                        </button>
                        {isAdmin && (
                          <button onClick={() => del(r)} className="rounded-md p-1.5 text-destructive hover:bg-destructive/10" title="Delete">
                            <Trash2 className="h-4 w-4" />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {open && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 p-4 backdrop-blur-sm">
          <div className="w-full max-w-2xl rounded-2xl border border-border bg-card shadow-2xl">
            <div className="flex items-center justify-between border-b border-border px-5 py-3">
              <h2 className="text-base font-bold">{isBn ? "নতুন দৈনিক ক্লোজিং" : "New Daily Closing"}</h2>
              <button onClick={() => setOpen(false)} className="rounded-md p-1 hover:bg-muted"><X className="h-4 w-4" /></button>
            </div>
            <div className="grid gap-3 p-5 md:grid-cols-2 max-h-[70vh] overflow-y-auto">
              <Field label={isBn ? "তারিখ" : "Date"}>
                <input type="date" value={form.closing_date} onChange={(e) => setForm({ ...form, closing_date: e.target.value })} className="input" />
              </Field>
              <Field label={isBn ? "শাখা" : "Branch"}>
                <select value={form.branch_id} onChange={(e) => setForm({ ...form, branch_id: e.target.value })} className="input">
                  <option value="">{isBn ? "সকল / প্রধান" : "All / Main"}</option>
                  {branches.map((b) => <option key={b.id} value={b.id}>{b.name}</option>)}
                </select>
              </Field>
              <Field label={isBn ? "ক্যাশিয়ার" : "Cashier"}>
                <select value={form.cashier_id} onChange={(e) => setForm({ ...form, cashier_id: e.target.value })} className="input">
                  <option value="">{isBn ? "— কেউ না —" : "— None —"}</option>
                  {cashiers.map((c) => <option key={c.id} value={c.id}>{c.full_name || "—"}</option>)}
                </select>
              </Field>
              <Field label={isBn ? "শিফট" : "Shift"}>
                <select value={form.shift} onChange={(e) => setForm({ ...form, shift: e.target.value })} className="input">
                  {SHIFTS.map((s) => <option key={s.value} value={s.value}>{isBn ? s.label_bn : s.label_en}</option>)}
                </select>
              </Field>

              <div className="md:col-span-2 flex items-center justify-between rounded-lg bg-muted/40 px-3 py-2 text-sm">
                <label className="flex items-center gap-2">
                  <input type="checkbox" checked={autoCalc} onChange={(e) => setAutoCalc(e.target.checked)} />
                  {isBn ? "সেলস/খরচ থেকে স্বয়ংক্রিয় হিসাব" : "Auto-fill from sales / expenses"}
                </label>
                <button onClick={loadAutoFigures} className="text-xs underline text-primary">
                  {isBn ? "রিফ্রেশ" : "Refresh figures"}
                </button>
              </div>

              <NumField label={isBn ? "ওপেনিং ক্যাশ" : "Opening Cash"} value={form.opening_cash} onChange={(v) => setForm({ ...form, opening_cash: v })} />
              <NumField label={isBn ? "ক্যাশ সেলস" : "Cash Sales"} value={form.cash_sales} onChange={(v) => setForm({ ...form, cash_sales: v })} />
              <NumField label={isBn ? "ডিউ কালেকশন" : "Due Collection"} value={form.due_collection} onChange={(v) => setForm({ ...form, due_collection: v })} />
              <NumField label={isBn ? "খরচ" : "Expense"} value={form.expense_amount} onChange={(v) => setForm({ ...form, expense_amount: v })} />
              <NumField label={isBn ? "সাপ্লায়ার পেমেন্ট" : "Supplier Payment"} value={form.supplier_payment} onChange={(v) => setForm({ ...form, supplier_payment: v })} />
              <NumField label={isBn ? "ব্যাংক ডিপোজিট" : "Bank Deposit"} value={form.bank_deposit} onChange={(v) => setForm({ ...form, bank_deposit: v })} />
              <NumField label={isBn ? "ক্যাশ আউট" : "Cash Out"} value={form.withdraw_amount} onChange={(v) => setForm({ ...form, withdraw_amount: v })} />
              <NumField label={isBn ? "প্রকৃত ক্লোজিং ক্যাশ" : "Actual Closing Cash"} value={form.closing_cash} onChange={(v) => setForm({ ...form, closing_cash: v })} />

              <div className="md:col-span-2 grid grid-cols-2 gap-3 rounded-lg border border-border bg-muted/30 p-3 text-sm">
                <div>
                  <div className="text-xs text-muted-foreground">{isBn ? "প্রত্যাশিত ক্যাশ (অটো)" : "Expected Cash (auto)"}</div>
                  <div className="text-lg font-bold">{expectedCash.toFixed(2)}</div>
                </div>
                <div>
                  <div className="text-xs text-muted-foreground">{isBn ? "পার্থক্য" : "Difference"}</div>
                  <div className={`text-lg font-bold ${Math.abs(difference) < 0.01 ? "" : difference < 0 ? "text-destructive" : "text-amber-600"}`}>
                    {difference.toFixed(2)}
                  </div>
                </div>
                {Math.abs(difference) > 0.01 && (
                  <div className="md:col-span-2 flex items-center gap-2 rounded-md bg-amber-500/10 px-2 py-1.5 text-xs text-amber-700">
                    <AlertTriangle className="h-3.5 w-3.5" />
                    {isBn ? "ক্যাশ মিসম্যাচ সতর্কতা" : "Cash mismatch warning"}
                  </div>
                )}
                {expectedCash < 0 && (
                  <div className="md:col-span-2 flex items-center gap-2 rounded-md bg-destructive/10 px-2 py-1.5 text-xs text-destructive">
                    <AlertTriangle className="h-3.5 w-3.5" />
                    {isBn ? "নেতিবাচক ব্যালেন্স!" : "Negative balance!"}
                  </div>
                )}
              </div>

              <div className="md:col-span-2">
                <Field label={isBn ? "নোট" : "Note"}>
                  <textarea value={form.note} onChange={(e) => setForm({ ...form, note: e.target.value })} className="input min-h-[60px]" />
                </Field>
              </div>
            </div>
            <div className="flex justify-end gap-2 border-t border-border px-5 py-3">
              <button onClick={() => setOpen(false)} className="rounded-lg border border-border px-4 py-2 text-sm">
                {isBn ? "বাতিল" : "Cancel"}
              </button>
              <button disabled={saving} onClick={() => save(false)} className="rounded-lg border border-border px-4 py-2 text-sm hover:bg-muted">
                {isBn ? "সংরক্ষণ" : "Save Draft"}
              </button>
              <button disabled={saving} onClick={() => save(true)} className="flex items-center gap-1.5 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-60">
                <Lock className="h-4 w-4" /> {isBn ? "ক্লোজ ও লক" : "Close & Lock"}
              </button>
            </div>
          </div>
        </div>
      )}

      <style>{`.input{width:100%;border:1px solid hsl(var(--border));background:hsl(var(--background));border-radius:0.5rem;padding:0.5rem 0.75rem;font-size:0.875rem}`}</style>
    </PageLayout>
  );
}

function SummaryCard({ icon, label, value, tone, isCount }: { icon: React.ReactNode; label: string; value: number; tone: "primary" | "success" | "warning" | "danger"; isCount?: boolean }) {
  const toneClass = {
    primary: "bg-primary/10 text-primary",
    success: "bg-emerald-500/10 text-emerald-600",
    warning: "bg-amber-500/10 text-amber-600",
    danger: "bg-destructive/10 text-destructive",
  }[tone];
  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>
        <span className={`rounded-md p-1.5 ${toneClass}`}>{icon}</span>
      </div>
      <div className="mt-2 text-xl font-bold">{isCount ? value : Number(value).toFixed(2)}</div>
    </div>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="block">
      <div className="mb-1 text-xs font-medium text-muted-foreground">{label}</div>
      {children}
    </label>
  );
}

function NumField({ label, value, onChange }: { label: string; value: number; onChange: (v: number) => void }) {
  return (
    <Field label={label}>
      <input
        type="number"
        step="0.01"
        value={value}
        onChange={(e) => onChange(Number(e.target.value || 0))}
        className="input text-right"
      />
    </Field>
  );
}
