"use client";

import { useState } from "react";
import { useLang } from "@/context/LanguageContext";
import {
  Alert,
  Button,
  Card,
  DatePicker,
  EmptyState,
  Input,
  Modal,
  PageHeader,
  PageLoader,
  Pagination,
  Select,
  StatCard,
  Textarea,
  usePagination,
} from "@/components/ui";
import { api, useApi } from "@/lib/client";
import { downloadCsv, formatBDT, formatDate } from "@/lib/utils";
import { PAYMENT_METHODS } from "@/lib/constants";
import { emsConfirm } from "@/components/ConfirmDialog";
import { DistributionDonut, MoneyBarsChart } from "@/components/charts";
import {
  IconDollar,
  IconDownload,
  IconEdit,
  IconFile,
  IconPlus,
  IconTrash,
  IconTrend,
  IconWallet,
} from "@/components/icons";

type EntryType = "INCOME" | "EXPENSE";

/** premium donut palette — teal family first for income, warm for expense */
const DONUT_COLORS = ["#24695c", "#5ec8b4", "#2e6b8f", "#8f6b2e", "#7a4b8f", "#b0446e", "#4b8f6b", "#8f4b4b"];

interface Head {
  id: number;
  name: string;
  nameBn: string | null;
  type: EntryType;
  isActive: boolean;
  entryCount: number;
  total: number;
  createdAt: string;
}

interface Entry {
  id: number;
  voucherNo: string;
  type: EntryType;
  amount: string;
  date: string;
  method: string;
  party: string | null;
  note: string | null;
  headId: number;
  head: { name: string; nameBn: string | null; type: EntryType };
  createdBy: { name: string } | null;
  createdAt: string;
}

interface HeadRow {
  name: string;
  nameBn: string | null;
  total: number;
  count: number;
}

interface Report {
  range: { from: string; to: string };
  totals: { income: number; expense: number; balance: number; count: number };
  incomeByHead: HeadRow[];
  expenseByHead: HeadRow[];
  headsCount: number;
  monthly: { key: string; label: string; income: number; expense: number }[];
}

interface Me {
  user: { institution: { name: string } | null } | null;
}

type Tab = "overview" | "heads" | "vouchers" | "report";

const emptyHead = { name: "", nameBn: "", type: "INCOME" as EntryType };
const emptyVoucher = { type: "INCOME" as EntryType, headId: "", date: "", amount: "", method: "CASH", party: "", note: "" };

function defaultFrom(): string {
  const now = new Date();
  const d = new Date(now.getFullYear(), now.getMonth() - 11, 1);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-01`;
}
function today(): string {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

export default function PortalAccountsPage() {
  const { t, locale } = useLang();
  const [tab, setTab] = useState<Tab>("overview");
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [busy, setBusy] = useState(false);

  // Report range (applied on demand so switching tabs keeps the chosen period)
  const [rangeForm, setRangeForm] = useState({ from: defaultFrom(), to: today() });
  const [appliedRange, setAppliedRange] = useState({ from: defaultFrom(), to: today() });

  const report = useApi<Report>(`/api/portal/accounts/report?from=${appliedRange.from}&to=${appliedRange.to}`);
  const headsData = useApi<{ heads: Head[] }>("/api/portal/accounts/heads");
  const entriesData = useApi<{ entries: Entry[]; totals: { income: number; expense: number } }>(
    "/api/portal/accounts/entries",
  );
  const me = useApi<Me>("/api/auth/me");

  // head modal
  const [headModal, setHeadModal] = useState(false);
  const [editingHead, setEditingHead] = useState<Head | null>(null);
  const [headForm, setHeadForm] = useState(emptyHead);

  // voucher modal
  const [voucherModal, setVoucherModal] = useState(false);
  const [voucherForm, setVoucherForm] = useState(emptyVoucher);

  // voucher filters (client-side)
  const [filterType, setFilterType] = useState("");
  const [filterHeadId, setFilterHeadId] = useState("");
  const [filterFrom, setFilterFrom] = useState("");
  const [filterTo, setFilterTo] = useState("");

  const heads = headsData.data?.heads ?? [];
  const allEntries = entriesData.data?.entries ?? [];

  const filteredEntries = allEntries.filter((e) => {
    if (filterType && e.type !== filterType) return false;
    if (filterHeadId && String(e.headId) !== filterHeadId) return false;
    if (filterFrom && e.date.slice(0, 10) < filterFrom) return false;
    if (filterTo && e.date.slice(0, 10) > filterTo) return false;
    return true;
  });

  const entriesPager = usePagination(filteredEntries, 10);
  const headsPager = usePagination(heads, 10);

  function reloadAll() {
    report.reload();
    headsData.reload();
    entriesData.reload();
  }

  /* ---------- Heads ---------- */
  function openHeadCreate() {
    setEditingHead(null);
    setHeadForm(emptyHead);
    setHeadModal(true);
  }
  function openHeadEdit(h: Head) {
    setEditingHead(h);
    setHeadForm({ name: h.name, nameBn: h.nameBn ?? "", type: h.type });
    setHeadModal(true);
  }
  async function submitHead(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setMessage(null);
    try {
      if (editingHead) {
        await api(`/api/portal/accounts/heads/${editingHead.id}`, {
          method: "PATCH",
          body: JSON.stringify({ name: headForm.name, nameBn: headForm.nameBn }),
        });
      } else {
        await api("/api/portal/accounts/heads", {
          method: "POST",
          body: JSON.stringify(headForm),
        });
      }
      setHeadModal(false);
      setMessage({ type: "success", text: t.common.savedSuccessfully });
      reloadAll();
    } catch (err) {
      setMessage({
        type: "error",
        text: err instanceof Error && err.message === "NAME_EXISTS" ? t.portal.accountsPage.headExists : t.common.tryAgain,
      });
    } finally {
      setBusy(false);
    }
  }
  async function removeHead(h: Head) {
    if (!(await emsConfirm({ message: t.common.confirmDelete, danger: true }))) return;
    try {
      await api(`/api/portal/accounts/heads/${h.id}`, { method: "DELETE" });
      reloadAll();
    } catch (err) {
      setMessage({
        type: "error",
        text: err instanceof Error && err.message === "HEAD_IN_USE" ? t.portal.accountsPage.headInUse : t.common.tryAgain,
      });
    }
  }

  /* ---------- Vouchers ---------- */
  function openVoucher(type: EntryType = "INCOME") {
    setVoucherForm({ ...emptyVoucher, type, date: today() });
    setVoucherModal(true);
  }
  async function submitVoucher(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setMessage(null);
    try {
      const res = await api<{ entry: Entry }>("/api/portal/accounts/entries", {
        method: "POST",
        body: JSON.stringify({
          headId: Number(voucherForm.headId),
          amount: Number(voucherForm.amount),
          date: voucherForm.date,
          method: voucherForm.method,
          party: voucherForm.party,
          note: voucherForm.note,
        }),
      });
      setVoucherModal(false);
      setMessage({ type: "success", text: `${t.portal.accountsPage.voucherCreated}: ${res.entry.voucherNo}` });
      reloadAll();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    } finally {
      setBusy(false);
    }
  }
  async function removeEntry(e: Entry) {
    if (!(await emsConfirm({ message: t.portal.accountsPage.deleteVoucherConfirm, danger: true }))) return;
    try {
      await api(`/api/portal/accounts/entries/${e.id}`, { method: "DELETE" });
      setMessage({ type: "success", text: t.portal.accountsPage.voucherDeleted });
      reloadAll();
    } catch {
      setMessage({ type: "error", text: t.common.tryAgain });
    }
  }

  /* ---------- Report helpers ---------- */
  function exportStatementCsv(r: Report) {
    const rows: (string | number)[][] = [
      [t.portal.accountsPage.statementOf],
      [t.portal.accountsPage.reportPeriod, `${r.range.from}`, "→", r.range.to],
      [],
      [t.portal.accountsPage.incomeStatement],
      [t.common.category, t.portal.accountsPage.voucherCount, t.common.amount],
      ...r.incomeByHead.map((h) => [locale === "bn" && h.nameBn ? h.nameBn : h.name, h.count, h.total]),
      [t.portal.accountsPage.grandTotal, r.incomeByHead.reduce((s, h) => s + h.count, 0), r.totals.income],
      [],
      [t.portal.accountsPage.expenseStatement],
      [t.common.category, t.portal.accountsPage.voucherCount, t.common.amount],
      ...r.expenseByHead.map((h) => [locale === "bn" && h.nameBn ? h.nameBn : h.name, h.count, h.total]),
      [t.portal.accountsPage.grandTotal, r.expenseByHead.reduce((s, h) => s + h.count, 0), r.totals.expense],
      [],
      [t.portal.accountsPage.surplus, r.totals.balance],
      [],
      [t.portal.accountsPage.monthlyBreakdown],
      [t.common.month, t.portal.accountsPage.income, t.portal.accountsPage.expense, t.portal.accountsPage.surplus],
      ...r.monthly.map((m) => [m.label, m.income, m.expense, m.income - m.expense]),
    ];
    downloadCsv(`accounts-statement-${r.range.from}-to-${r.range.to}`, rows);
  }

  function exportVouchersCsv() {
    const rows: (string | number)[][] = [
      [
        t.portal.accountsPage.voucherNo,
        t.common.date,
        t.portal.accountsPage.head,
        t.common.type,
        t.portal.accountsPage.party,
        t.common.method,
        t.common.amount,
        t.common.note,
      ],
      ...filteredEntries.map((e) => [
        e.voucherNo,
        e.date.slice(0, 10),
        locale === "bn" && e.head.nameBn ? e.head.nameBn : e.head.name,
        e.type === "INCOME" ? t.portal.accountsPage.income : t.portal.accountsPage.expense,
        e.party ?? "",
        t.methods[e.method as keyof typeof t.methods],
        Number(e.amount),
        e.note ?? "",
      ]),
    ];
    downloadCsv("accounts-vouchers", rows);
  }

  function printStatement(r: Report) {
    const instName = me.data?.user?.institution?.name ?? "IncrelogEMS";
    const headName = (h: HeadRow) => (locale === "bn" && h.nameBn ? h.nameBn : h.name);
    const money = (n: number) => formatBDT(n, locale);
    const headTable = (rows: HeadRow[], total: number) => `
      <table>
        <thead><tr><th>${t.common.category}</th><th>${t.portal.accountsPage.voucherCount}</th><th>${t.common.amount}</th></tr></thead>
        <tbody>
          ${rows
            .map(
              (h) =>
                `<tr><td>${headName(h)}</td><td style="text-align:center">${h.count}</td><td style="text-align:right">${money(h.total)}</td></tr>`,
            )
            .join("")}
          <tr class="total"><td>${t.portal.accountsPage.grandTotal}</td><td style="text-align:center">${rows.reduce((s, h) => s + h.count, 0)}</td><td style="text-align:right">${money(total)}</td></tr>
        </tbody>
      </table>`;
    const html = `<!DOCTYPE html>
<html lang="${locale}">
<head>
<meta charset="utf-8"/>
<title>${t.portal.accountsPage.reportTitle}</title>
<style>
  body { font-family: 'Montserrat', 'Noto Sans Bengali', sans-serif; color: #2c323f; margin: 32px; }
  h1 { font-size: 20px; margin: 0 0 2px; }
  h2 { font-size: 14px; margin: 22px 0 6px; color: #24695c; }
  .sub { color: #718096; font-size: 12px; margin: 0 0 14px; }
  table { width: 100%; border-collapse: collapse; font-size: 12px; }
  th, td { border: 1px solid #d9e1ec; padding: 6px 10px; }
  th { background: #f0f4f9; text-align: left; }
  tr.total td { font-weight: 700; background: #f7fafc; }
  .summary { display: flex; gap: 24px; margin: 14px 0; font-size: 13px; }
  .summary div { border: 1px solid #d9e1ec; border-radius: 8px; padding: 8px 16px; }
  .summary b { display: block; font-size: 16px; margin-top: 2px; }
</style>
</head>
<body>
  <h1>${instName}</h1>
  <p class="sub">${t.portal.accountsPage.statementOf} — ${t.portal.accountsPage.reportPeriod}: ${formatDate(r.range.from, locale)} → ${formatDate(r.range.to, locale)} | ${t.portal.accountsPage.generatedOn}: ${formatDate(new Date().toISOString(), locale)}</p>
  <div class="summary">
    <div>${t.portal.accountsPage.totalIncome}<b style="color:#24695c">${money(r.totals.income)}</b></div>
    <div>${t.portal.accountsPage.totalExpense}<b style="color:#e02424">${money(r.totals.expense)}</b></div>
    <div>${t.portal.accountsPage.surplus}<b style="color:${r.totals.balance >= 0 ? "#24695c" : "#e02424"}">${money(r.totals.balance)}</b></div>
  </div>
  <h2>${t.portal.accountsPage.incomeStatement}</h2>
  ${headTable(r.incomeByHead, r.totals.income)}
  <h2>${t.portal.accountsPage.expenseStatement}</h2>
  ${headTable(r.expenseByHead, r.totals.expense)}
  <h2>${t.portal.accountsPage.monthlyBreakdown}</h2>
  <table>
    <thead><tr><th>${t.common.month}</th><th>${t.portal.accountsPage.income}</th><th>${t.portal.accountsPage.expense}</th><th>${t.portal.accountsPage.surplus}</th></tr></thead>
    <tbody>
      ${r.monthly
        .map(
          (m) =>
            `<tr><td>${m.label}</td><td style="text-align:right">${money(m.income)}</td><td style="text-align:right">${money(m.expense)}</td><td style="text-align:right">${money(m.income - m.expense)}</td></tr>`,
        )
        .join("")}
    </tbody>
  </table>
</body>
</html>`;
    const w = window.open("", "_blank", "width=900,height=700");
    if (!w) return;
    w.document.write(html);
    w.document.close();
    w.focus();
    setTimeout(() => w.print(), 350);
  }

  const r = report.data;
  const voucherHeads = heads.filter((h) => h.isActive && h.type === voucherForm.type);

  const tabs: { id: Tab; label: string }[] = [
    { id: "overview", label: t.portal.accountsPage.tabOverview },
    { id: "heads", label: t.portal.accountsPage.tabHeads },
    { id: "vouchers", label: t.portal.accountsPage.tabVouchers },
    { id: "report", label: t.portal.accountsPage.tabReport },
  ];

  return (
    <div>
      <PageHeader
        title={t.portal.accountsPage.title}
        subtitle={t.portal.accountsPage.subtitle}
        action={
          <Button onClick={() => openVoucher()}>
            <IconPlus className="svg-16" />
            <span className="ms-1">{t.portal.accountsPage.newVoucher}</span>
          </Button>
        }
      />

      {message && (
        <div className="mb-4">
          <Alert type={message.type} onClose={() => setMessage(null)}>{message.text}</Alert>
        </div>
      )}

      {/* Tabs */}
      <ul className="nav nav-tabs mb-4">
        {tabs.map((x) => (
          <li className="nav-item" key={x.id}>
            <button className={`nav-link f-w-600 ${tab === x.id ? "active" : ""}`} type="button" onClick={() => setTab(x.id)}>
              {x.label}
            </button>
          </li>
        ))}
      </ul>

      {tab === "overview" && (
        <>
          <div className="row g-4 mb-4">
            <div className="col-xl-3 col-md-6">
              <StatCard label={t.portal.accountsPage.totalIncome} value={formatBDT(r?.totals.income ?? 0, locale)} icon={<IconWallet />} accent="teal" />
            </div>
            <div className="col-xl-3 col-md-6">
              <StatCard label={t.portal.accountsPage.totalExpense} value={formatBDT(r?.totals.expense ?? 0, locale)} icon={<IconDollar />} accent="orange" />
            </div>
            <div className="col-xl-3 col-md-6">
              <StatCard
                label={t.portal.accountsPage.balance}
                value={formatBDT(r?.totals.balance ?? 0, locale)}
                icon={<IconTrend />}
                accent={(r?.totals.balance ?? 0) >= 0 ? "blue" : "red"}
              />
            </div>
            <div className="col-xl-3 col-md-6">
              <StatCard label={t.portal.accountsPage.voucherCount} value={String(r?.totals.count ?? 0)} icon={<IconFile />} accent="purple" hint={`${heads.length} ${t.portal.accountsPage.tabHeads}`} />
            </div>
          </div>

          <div className="row g-4">
            <div className="col-xl-7">
              <Card title={t.portal.accountsPage.incomeVsExpense} icon={<IconTrend className="svg-20" />}>
                <MoneyBarsChart
                  labels={(r?.monthly ?? []).map((m) => m.label)}
                  series={[
                    { name: t.portal.accountsPage.income, data: (r?.monthly ?? []).map((m) => m.income), colors: ["#5ec8b4", "#24695c"] },
                    { name: t.portal.accountsPage.expense, data: (r?.monthly ?? []).map((m) => m.expense), colors: ["#f8c47e", "#f29d38"] },
                  ]}
                  formatValue={(n) => formatBDT(n, locale)}
                />
              </Card>
            </div>
            <div className="col-xl-5">
              <Card title={t.portal.accountsPage.recentEntries} icon={<IconFile className="svg-20" />}>
                {allEntries.length === 0 ? (
                  <EmptyState icon={<IconFile />} title={t.portal.accountsPage.noVouchers} />
                ) : (
                  <div className="table-responsive">
                    <table className="table table-hover align-middle mb-0">
                      <thead className="ems-table-head">
                        <tr>
                          <th>{t.portal.accountsPage.voucherNo}</th>
                          <th>{t.portal.accountsPage.head}</th>
                          <th className="text-end">{t.common.amount}</th>
                        </tr>
                      </thead>
                      <tbody>
                        {allEntries.slice(0, 6).map((e) => (
                          <tr key={e.id}>
                            <td>
                              <p className="mb-0 f-w-600 ems-fs-12">{e.voucherNo}</p>
                              <p className="mb-0 ems-fs-11 text-muted">{formatDate(e.date, locale)}</p>
                            </td>
                            <td>
                              <span className={`badge ${e.type === "INCOME" ? "badge-success" : "badge-danger"}`}>
                                {e.type === "INCOME" ? t.portal.accountsPage.income : t.portal.accountsPage.expense}
                              </span>{" "}
                              <span className="ems-fs-12">{locale === "bn" && e.head.nameBn ? e.head.nameBn : e.head.name}</span>
                            </td>
                            <td className={`text-end f-w-700 ems-fs-13 ${e.type === "INCOME" ? "ems-text-teal" : "text-danger"}`}>
                              {e.type === "INCOME" ? "+" : "−"}{formatBDT(e.amount, locale)}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </Card>
            </div>
          </div>
        </>
      )}

      {tab === "heads" && (
        <div className="card">
          <div className="card-header d-flex justify-content-between align-items-center">
            <h5 className="mb-0">{t.portal.accountsPage.tabHeads}</h5>
            <Button size="sm" onClick={openHeadCreate}>
              <IconPlus className="svg-16" />
              <span className="ms-1">{t.portal.accountsPage.newHead}</span>
            </Button>
          </div>
          {headsData.loading ? (
            <div className="card-body"><PageLoader text={t.common.loading} /></div>
          ) : heads.length === 0 ? (
            <div className="card-body">
              <EmptyState icon={<IconFile />} title={t.portal.accountsPage.noHeads} />
            </div>
          ) : (
            <>
              <div className="table-responsive">
              <table className="table table-hover align-middle mb-0">
                <thead className="ems-table-head">
                  <tr>
                    <th>{t.portal.accountsPage.headName}</th>
                    <th>{t.common.type}</th>
                    <th className="text-center">{t.portal.accountsPage.entriesCount}</th>
                    <th className="text-end">{t.common.total}</th>
                    <th className="text-end">{t.common.actions}</th>
                  </tr>
                </thead>
                <tbody>
                  {headsPager.paged.map((h) => (
                    <tr key={h.id} className={h.isActive ? "" : "opacity-50"}>
                      <td>
                        <p className="mb-0 f-w-600">{locale === "bn" && h.nameBn ? h.nameBn : h.name}</p>
                        {!h.isActive && <span className="badge badge-secondary mt-1">{t.common.inactive}</span>}
                      </td>
                      <td>
                        <span className={`badge ${h.type === "INCOME" ? "badge-success" : "badge-danger"}`}>
                          {h.type === "INCOME" ? t.portal.accountsPage.income : t.portal.accountsPage.expense}
                        </span>
                      </td>
                      <td className="text-center">{h.entryCount}</td>
                      <td className="text-end f-w-700">{formatBDT(h.total, locale)}</td>
                      <td className="text-end">
                        <div className="d-inline-flex gap-1">
                          <Button size="sm" variant="secondary" onClick={() => openHeadEdit(h)} title={t.common.edit}>
                            <IconEdit className="svg-16" />
                          </Button>
                          <Button size="sm" variant="danger" onClick={() => removeHead(h)} title={t.common.delete}>
                            <IconTrash className="svg-16" />
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              </div>
              <Pagination {...headsPager} onPageChange={headsPager.setPage} onSizeChange={headsPager.setSize} />
            </>
          )}
        </div>
      )}

      {tab === "vouchers" && (
        <div className="card">
          <div className="card-header">
            <div className="row g-2 align-items-end">
              <div className="col-md-2">
                <Select label={t.common.type} value={filterType} onChange={(e) => setFilterType(e.target.value)}>
                  <option value="">{t.common.all}</option>
                  <option value="INCOME">{t.portal.accountsPage.income}</option>
                  <option value="EXPENSE">{t.portal.accountsPage.expense}</option>
                </Select>
              </div>
              <div className="col-md-3">
                <Select label={t.portal.accountsPage.head} value={filterHeadId} onChange={(e) => setFilterHeadId(e.target.value)}>
                  <option value="">{t.portal.accountsPage.allHeads}</option>
                  {heads.map((h) => (
                    <option key={h.id} value={h.id}>
                      {locale === "bn" && h.nameBn ? h.nameBn : h.name}
                    </option>
                  ))}
                </Select>
              </div>
              <div className="col-md-2">
                <DatePicker label={t.portal.accountsPage.fromDate} value={filterFrom} onChange={(e) => setFilterFrom(e.target.value)} />
              </div>
              <div className="col-md-2">
                <DatePicker label={t.portal.accountsPage.toDate} value={filterTo} onChange={(e) => setFilterTo(e.target.value)} />
              </div>
              <div className="col-md-3 text-end">
                <Button variant="secondary" size="sm" onClick={exportVouchersCsv} disabled={filteredEntries.length === 0}>
                  <IconDownload className="svg-16" />
                  <span className="ms-1">{t.portal.accountsPage.exportVouchers}</span>
                </Button>
              </div>
            </div>
          </div>
          {entriesData.loading ? (
            <div className="card-body"><PageLoader text={t.common.loading} /></div>
          ) : filteredEntries.length === 0 ? (
            <div className="card-body">
              <EmptyState icon={<IconFile />} title={t.portal.accountsPage.noVouchers} />
            </div>
          ) : (
            <>
              <div className="table-responsive">
              <table className="table table-hover align-middle mb-0">
                <thead className="ems-table-head">
                  <tr>
                    <th>{t.portal.accountsPage.voucherNo}</th>
                    <th>{t.common.date}</th>
                    <th>{t.portal.accountsPage.head}</th>
                    <th>{t.portal.accountsPage.party}</th>
                    <th>{t.common.method}</th>
                    <th className="text-end">{t.common.amount}</th>
                    <th className="text-end">{t.common.actions}</th>
                  </tr>
                </thead>
                <tbody>
                  {entriesPager.paged.map((e) => (
                    <tr key={e.id}>
                      <td className="f-w-600 ems-fs-12">{e.voucherNo}</td>
                      <td className="ems-fs-12 text-muted">{formatDate(e.date, locale)}</td>
                      <td>
                        <span className={`badge ${e.type === "INCOME" ? "badge-success" : "badge-danger"} me-1`}>
                          {e.type === "INCOME" ? t.portal.accountsPage.income : t.portal.accountsPage.expense}
                        </span>
                        <span className="ems-fs-12">{locale === "bn" && e.head.nameBn ? e.head.nameBn : e.head.name}</span>
                      </td>
                      <td className="ems-fs-12">{e.party ?? "—"}</td>
                      <td>
                        <span className="badge badge-secondary">{t.methods[e.method as keyof typeof t.methods]}</span>
                      </td>
                      <td className={`text-end f-w-700 ${e.type === "INCOME" ? "ems-text-teal" : "text-danger"}`}>
                        {e.type === "INCOME" ? "+" : "−"}{formatBDT(e.amount, locale)}
                      </td>
                      <td className="text-end">
                        <Button size="sm" variant="danger" onClick={() => removeEntry(e)} title={t.common.delete}>
                          <IconTrash className="svg-16" />
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              </div>
              <Pagination {...entriesPager} onPageChange={entriesPager.setPage} onSizeChange={entriesPager.setSize} />
            </>
          )}
        </div>
      )}

      {tab === "report" && (
        <div>
          {/* Range picker */}
          <div className="card mb-4">
            <div className="card-body">
              <div className="row g-3 align-items-end">
                <div className="col-md-3">
                  <DatePicker label={t.portal.accountsPage.fromDate} value={rangeForm.from} max={rangeForm.to} onChange={(e) => setRangeForm({ ...rangeForm, from: e.target.value })} />
                </div>
                <div className="col-md-3">
                  <DatePicker label={t.portal.accountsPage.toDate} value={rangeForm.to} min={rangeForm.from} max={today()} onChange={(e) => setRangeForm({ ...rangeForm, to: e.target.value })} />
                </div>
                <div className="col-md-6 text-md-end">
                  <div className="d-inline-flex gap-2">
                    <Button
                      variant="secondary"
                      onClick={() => {
                        setRangeForm({ from: defaultFrom(), to: today() });
                        setAppliedRange({ from: defaultFrom(), to: today() });
                      }}
                    >
                      {t.portal.accountsPage.reset}
                    </Button>
                    <Button
                      disabled={!rangeForm.from || !rangeForm.to}
                      onClick={() => setAppliedRange({ ...rangeForm })}
                    >
                      {t.portal.accountsPage.apply}
                    </Button>
                    {r && (
                      <>
                        <Button variant="secondary" onClick={() => exportStatementCsv(r)}>
                          <IconDownload className="svg-16" />
                          <span className="ms-1">{t.portal.accountsPage.exportCsv}</span>
                        </Button>
                        <Button variant="secondary" onClick={() => printStatement(r)}>
                          <IconFile className="svg-16" />
                          <span className="ms-1">{t.portal.accountsPage.print}</span>
                        </Button>
                      </>
                    )}
                  </div>
                </div>
              </div>
            </div>
          </div>

          {report.loading ? (
            <PageLoader text={t.common.loading} />
          ) : !r ? (
            <div className="card"><EmptyState title={t.common.tryAgain} /></div>
          ) : r.totals.count === 0 ? (
            <div className="card">
              <EmptyState icon={<IconFile />} title={t.portal.accountsPage.noReportData} />
            </div>
          ) : (
            <>
              <div className="row g-4 mb-4">
                <div className="col-md-4">
                  <StatCard label={t.portal.accountsPage.totalIncome} value={formatBDT(r.totals.income, locale)} icon={<IconWallet />} accent="teal" />
                </div>
                <div className="col-md-4">
                  <StatCard label={t.portal.accountsPage.totalExpense} value={formatBDT(r.totals.expense, locale)} icon={<IconDollar />} accent="orange" />
                </div>
                <div className="col-md-4">
                  <StatCard
                    label={t.portal.accountsPage.surplus}
                    value={formatBDT(r.totals.balance, locale)}
                    icon={<IconTrend />}
                    accent={r.totals.balance >= 0 ? "blue" : "red"}
                  />
                </div>
              </div>

              <div className="row g-4 mb-4">
                <div className="col-xl-6">
                  <Card title={t.portal.accountsPage.incomeDistribution} icon={<IconWallet className="svg-20" />}>
                    <DistributionDonut
                      slices={(r.incomeByHead ?? []).filter((h) => h.total > 0).map((h, i) => ({
                        label: locale === "bn" && h.nameBn ? h.nameBn : h.name,
                        value: h.total,
                        color: DONUT_COLORS[i % DONUT_COLORS.length],
                      }))}
                      formatValue={(n) => formatBDT(n, locale)}
                      centerLabel={t.portal.accountsPage.income}
                      centerValue={formatBDT(r.totals.income, locale)}
                    />
                  </Card>
                </div>
                <div className="col-xl-6">
                  <Card title={t.portal.accountsPage.expenseDistribution} icon={<IconDollar className="svg-20" />}>
                    <DistributionDonut
                      slices={(r.expenseByHead ?? []).filter((h) => h.total > 0).map((h, i) => ({
                        label: locale === "bn" && h.nameBn ? h.nameBn : h.name,
                        value: h.total,
                        color: DONUT_COLORS[(i + 3) % DONUT_COLORS.length],
                      }))}
                      formatValue={(n) => formatBDT(n, locale)}
                      centerLabel={t.portal.accountsPage.expense}
                      centerValue={formatBDT(r.totals.expense, locale)}
                    />
                  </Card>
                </div>
              </div>

              <div className="row g-4 mb-4">
                <div className="col-xl-6">
                  <Card title={t.portal.accountsPage.incomeStatement} icon={<IconWallet className="svg-20" />}>
                    <div className="table-responsive">
                      <table className="table table-hover align-middle mb-0">
                        <thead className="ems-table-head">
                          <tr>
                            <th>{t.common.category}</th>
                            <th className="text-center">{t.portal.accountsPage.voucherCount}</th>
                            <th className="text-end">{t.common.amount}</th>
                          </tr>
                        </thead>
                        <tbody>
                          {r.incomeByHead.map((h) => (
                            <tr key={h.name}>
                              <td className="f-w-600">{locale === "bn" && h.nameBn ? h.nameBn : h.name}</td>
                              <td className="text-center">{h.count}</td>
                              <td className="text-end f-w-700 ems-text-teal">{formatBDT(h.total, locale)}</td>
                            </tr>
                          ))}
                          <tr>
                            <td className="f-w-800">{t.portal.accountsPage.grandTotal}</td>
                            <td className="text-center f-w-800">{r.incomeByHead.reduce((s, h) => s + h.count, 0)}</td>
                            <td className="text-end f-w-800 ems-text-teal">{formatBDT(r.totals.income, locale)}</td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </Card>
                </div>
                <div className="col-xl-6">
                  <Card title={t.portal.accountsPage.expenseStatement} icon={<IconDollar className="svg-20" />}>
                    <div className="table-responsive">
                      <table className="table table-hover align-middle mb-0">
                        <thead className="ems-table-head">
                          <tr>
                            <th>{t.common.category}</th>
                            <th className="text-center">{t.portal.accountsPage.voucherCount}</th>
                            <th className="text-end">{t.common.amount}</th>
                          </tr>
                        </thead>
                        <tbody>
                          {r.expenseByHead.map((h) => (
                            <tr key={h.name}>
                              <td className="f-w-600">{locale === "bn" && h.nameBn ? h.nameBn : h.name}</td>
                              <td className="text-center">{h.count}</td>
                              <td className="text-end f-w-700 text-danger">{formatBDT(h.total, locale)}</td>
                            </tr>
                          ))}
                          <tr>
                            <td className="f-w-800">{t.portal.accountsPage.grandTotal}</td>
                            <td className="text-center f-w-800">{r.expenseByHead.reduce((s, h) => s + h.count, 0)}</td>
                            <td className="text-end f-w-800 text-danger">{formatBDT(r.totals.expense, locale)}</td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </Card>
                </div>
              </div>

              <Card title={t.portal.accountsPage.monthlyBreakdown} icon={<IconTrend className="svg-20" />}>
                <div className="table-responsive">
                  <table className="table table-hover align-middle mb-0">
                    <thead className="ems-table-head">
                      <tr>
                        <th>{t.common.month}</th>
                        <th className="text-end">{t.portal.accountsPage.income}</th>
                        <th className="text-end">{t.portal.accountsPage.expense}</th>
                        <th className="text-end">{t.portal.accountsPage.surplus}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {r.monthly.map((m) => (
                        <tr key={m.key}>
                          <td className="f-w-600">{m.label}</td>
                          <td className="text-end ems-text-teal">{m.income > 0 ? formatBDT(m.income, locale) : "—"}</td>
                          <td className="text-end text-danger">{m.expense > 0 ? formatBDT(m.expense, locale) : "—"}</td>
                          <td className={`text-end f-w-700 ${m.income - m.expense >= 0 ? "ems-text-teal" : "text-danger"}`}>
                            {m.income || m.expense ? formatBDT(m.income - m.expense, locale) : "—"}
                          </td>
                        </tr>
                      ))}
                      <tr>
                        <td className="f-w-800">{t.portal.accountsPage.grandTotal}</td>
                        <td className="text-end f-w-800 ems-text-teal">{formatBDT(r.totals.income, locale)}</td>
                        <td className="text-end f-w-800 text-danger">{formatBDT(r.totals.expense, locale)}</td>
                        <td className="text-end f-w-800">{formatBDT(r.totals.balance, locale)}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </Card>
            </>
          )}
        </div>
      )}

      {/* Head modal */}
      <Modal open={headModal} onClose={() => setHeadModal(false)} title={editingHead ? t.portal.accountsPage.editHead : t.portal.accountsPage.newHead}>
        <form className="theme-form" onSubmit={submitHead}>
          <div className="row">
            <div className="col-md-6">
              <Input label={t.portal.accountsPage.headName} required value={headForm.name} onChange={(e) => setHeadForm({ ...headForm, name: e.target.value })} />
            </div>
            <div className="col-md-6">
              <Input label={t.portal.accountsPage.headNameBn} value={headForm.nameBn} onChange={(e) => setHeadForm({ ...headForm, nameBn: e.target.value })} />
            </div>
            {!editingHead && (
              <div className="col-md-6">
                <Select
                  label={t.common.type}
                  value={headForm.type}
                  onChange={(e) => setHeadForm({ ...headForm, type: e.target.value as EntryType })}
                >
                  <option value="INCOME">{t.portal.accountsPage.income}</option>
                  <option value="EXPENSE">{t.portal.accountsPage.expense}</option>
                </Select>
              </div>
            )}
          </div>
          <div className="d-flex justify-content-end gap-2">
            <Button type="button" variant="secondary" onClick={() => setHeadModal(false)}>
              {t.common.cancel}
            </Button>
            <Button type="submit" loading={busy} disabled={!headForm.name.trim()}>
              {editingHead ? t.common.saveChanges : t.common.create}
            </Button>
          </div>
        </form>
      </Modal>

      {/* Voucher modal */}
      <Modal open={voucherModal} onClose={() => setVoucherModal(false)} title={t.portal.accountsPage.newVoucher}>
        <form className="theme-form" onSubmit={submitVoucher}>
          <div className="row">
            <div className="col-md-6">
              <Select
                label={t.common.type}
                value={voucherForm.type}
                onChange={(e) => setVoucherForm({ ...voucherForm, type: e.target.value as EntryType, headId: "" })}
              >
                <option value="INCOME">{t.portal.accountsPage.income}</option>
                <option value="EXPENSE">{t.portal.accountsPage.expense}</option>
              </Select>
            </div>
            <div className="col-md-6">
              <Select
                label={t.portal.accountsPage.selectHead}
                value={voucherForm.headId}
                onChange={(e) => setVoucherForm({ ...voucherForm, headId: e.target.value })}
                required
              >
                <option value="">— {t.portal.accountsPage.selectHead} —</option>
                {voucherHeads.map((h) => (
                  <option key={h.id} value={h.id}>
                    {locale === "bn" && h.nameBn ? h.nameBn : h.name}
                  </option>
                ))}
              </Select>
            </div>
            <div className="col-md-6">
              <DatePicker label={t.common.date} value={voucherForm.date} max={today()} onChange={(e) => setVoucherForm({ ...voucherForm, date: e.target.value })} />
            </div>
            <div className="col-md-6">
              <Input
                label={t.common.amount}
                type="number"
                min="1"
                step="0.01"
                required
                value={voucherForm.amount}
                onChange={(e) => setVoucherForm({ ...voucherForm, amount: e.target.value })}
              />
            </div>
            <div className="col-md-6">
              <Select label={t.common.method} value={voucherForm.method} onChange={(e) => setVoucherForm({ ...voucherForm, method: e.target.value })}>
                {PAYMENT_METHODS.map((m) => (
                  <option key={m} value={m}>
                    {t.methods[m as keyof typeof t.methods]}
                  </option>
                ))}
              </Select>
            </div>
            <div className="col-md-6">
              <Input label={t.portal.accountsPage.party} value={voucherForm.party} onChange={(e) => setVoucherForm({ ...voucherForm, party: e.target.value })} />
            </div>
            <div className="col-md-12">
              <Textarea label={t.common.note} value={voucherForm.note} onChange={(e) => setVoucherForm({ ...voucherForm, note: e.target.value })} />
            </div>
          </div>
          {heads.filter((h) => h.type === voucherForm.type).length === 0 && (
            <Alert type="error">{t.portal.accountsPage.noHeads}</Alert>
          )}
          <div className="d-flex justify-content-end gap-2">
            <Button type="button" variant="secondary" onClick={() => setVoucherModal(false)}>
              {t.common.cancel}
            </Button>
            <Button
              type="submit"
              loading={busy}
              disabled={!voucherForm.headId || !voucherForm.date || !(Number(voucherForm.amount) > 0)}
            >
              {t.common.save}
            </Button>
          </div>
        </form>
      </Modal>
    </div>
  );
}
