import { Printer } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useRows, money, type Row } from "@/lib/crud";

type DocumentKind = "invoice" | "quotation" | "receipt" | "payment";
type LineItem = { label: string; detail?: string; amount: number };

const num = (value: unknown) => Number(value ?? 0);
const text = (value: unknown, fallback = "—") => {
  const raw = String(value ?? "").trim() || fallback;
  return raw.replace(/[&<>'"]/g, (character) => ({
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    "'": "&#39;",
    '"': "&quot;",
  })[character] ?? character);
};

function formatDate(value: unknown) {
  if (!value) return "—";
  const date = new Date(`${String(value).slice(0, 10)}T00:00:00`);
  if (Number.isNaN(date.getTime())) return text(value);
  return date.toLocaleDateString(undefined, { day: "2-digit", month: "short", year: "numeric" });
}

function formatPeriod(value: unknown) {
  const match = /^(\d{4})-(\d{2})/.exec(String(value ?? ""));
  if (!match) return text(value);
  return new Date(Number(match[1]), Number(match[2]) - 1, 1).toLocaleDateString(undefined, {
    month: "long",
    year: "numeric",
  });
}

const css = `
  * { box-sizing: border-box; }
  :root { --ink: #12372a; --brand: #2ca01c; --brand-soft: #eaf4e7; --paper: #ffffff; --canvas: #f3f5f4; --line: #dfe6e1; --muted: #66736c; --danger: #c92a2a; }
  html, body { margin: 0; padding: 0; background: var(--canvas); color: var(--ink); }
  body { font-family: 'DM Sans', Arial, sans-serif; padding: 36px 18px; }
  .document { width: min(820px, 100%); min-height: 1060px; margin: 0 auto; background: var(--paper); border: 1px solid var(--line); border-radius: 8px; box-shadow: 0 20px 50px rgba(18,55,42,.1); display: flex; flex-direction: column; overflow: hidden; }
  .masthead { padding: 46px 48px 34px; border-top: 7px solid var(--brand); border-bottom: 1px solid var(--line); background: var(--paper); }
  .masthead-inner { display: flex; justify-content: space-between; align-items: flex-start; gap: 48px; }
  .brand { display: flex; align-items: center; gap: 12px; }
  .logo { width: 42px; height: 42px; border-radius: 6px; display: grid; place-items: center; background: var(--ink); color: var(--paper); font: 700 21px 'Space Grotesk', sans-serif; }
  .brand-name { font: 700 24px 'Space Grotesk', sans-serif; }
  .company { margin-top: 18px; color: var(--muted); font-size: 11px; line-height: 1.7; }
  .company strong { display: block; color: var(--ink); font-size: 13px; }
  .title-block { text-align: right; }
  .doc-title { margin: 0 0 16px; color: var(--ink); font: 500 40px 'Space Grotesk', sans-serif; text-transform: uppercase; }
  .document-standard { color: var(--muted); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .09em; }
  .meta-grid { display: grid; grid-template-columns: repeat(3, 1fr); padding: 0 48px; border-bottom: 1px solid var(--line); }
  .meta-cell { min-height: 92px; padding: 24px 24px 24px 0; }
  .meta-cell + .meta-cell { padding-left: 24px; border-left: 1px solid var(--line); }
  .meta-cell:last-child { padding-right: 0; }
  .eyebrow { margin: 0 0 8px; color: var(--muted); font-size: 9px; font-weight: 700; text-transform: uppercase; letter-spacing: .1em; }
  .meta-cell:first-child .eyebrow, .amount-panel .eyebrow { color: var(--brand); }
  .meta-value { margin: 0; font: 600 16px 'Space Grotesk', sans-serif; }
  .meta-cell:last-child .meta-value { font-size: 21px; font-weight: 700; }
  .content { flex: 1; padding: 38px 48px 44px; }
  .party-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 48px; margin-bottom: 34px; }
  .party-name { margin: 0 0 5px; font: 700 19px 'Space Grotesk', sans-serif; }
  .small { color: var(--muted); font-size: 12px; line-height: 1.65; }
  .context { padding: 0 0 0 24px; border-left: 2px solid var(--brand); }
  .context-row { display: flex; justify-content: space-between; gap: 18px; padding: 5px 0; font-size: 12px; }
  .context-row span:first-child { color: var(--muted); }
  .context-row strong { text-align: right; }
  table { width: 100%; border-collapse: collapse; }
  th { padding: 12px 10px; color: var(--muted); border-bottom: 2px solid var(--ink); font-size: 9px; text-align: left; text-transform: uppercase; letter-spacing: .1em; }
  th:first-child, td:first-child { padding-left: 0; }
  th:last-child, td:last-child { padding-right: 0; text-align: right; }
  td { padding: 17px 10px; border-bottom: 1px solid var(--line); font-size: 12px; }
  .line-title { font: 600 14px 'Space Grotesk', sans-serif; }
  .line-detail { margin-top: 3px; color: var(--muted); font-size: 10px; }
  .summary { display: grid; grid-template-columns: 1fr 285px; gap: 48px; margin-top: 30px; }
  .payment-box { align-self: start; padding: 18px; border-left: 3px solid var(--brand); background: var(--brand-soft); }
  .payment-box p { margin: 4px 0; }
  .total-row { display: flex; justify-content: space-between; padding: 7px 0; color: var(--muted); font-size: 12px; }
  .total-row strong { color: var(--ink); }
  .grand-total { margin-top: 7px; padding-top: 14px; border-top: 2px solid var(--ink); color: var(--ink); font: 700 18px 'Space Grotesk', sans-serif; }
  .grand-total span:last-child { color: var(--brand); }
  .status { display: inline-block; margin-top: 12px; padding: 5px 10px; color: var(--brand); border: 1px solid var(--brand); border-radius: 999px; font: 700 10px 'Space Grotesk', sans-serif; text-transform: uppercase; }
  .statement-table td { padding-top: 12px; padding-bottom: 12px; }
  .credit { color: var(--brand); font-weight: 700; }
  .debit { color: var(--ink); font-weight: 700; }
  .balance-due { color: var(--danger) !important; font-weight: 700; }
  .footer { margin-top: auto; padding: 25px 48px; border-top: 1px solid var(--line); display: grid; grid-template-columns: 1fr auto; gap: 36px; color: var(--muted); background: var(--canvas); font-size: 9px; line-height: 1.6; }
  .footer strong { color: var(--ink); text-transform: uppercase; letter-spacing: .08em; }
  .verify { text-align: right; white-space: nowrap; }
  .bottom-bar { height: 6px; background: var(--brand); }
  @page { size: A4; margin: 0; }
  @media print { html, body { background: var(--paper); } body { padding: 0; } .document { width: 100%; min-height: 100vh; border: 0; border-radius: 0; box-shadow: none; } }
  @media (max-width: 650px) { body { padding: 0; } .document { border-radius: 0; } .masthead, .content { padding-left: 24px; padding-right: 24px; } .masthead-inner { gap: 20px; } .doc-title { font-size: 28px; } .meta-grid { padding: 0 24px; } .meta-cell { padding: 18px 10px 18px 0; } .meta-cell + .meta-cell { padding-left: 10px; } .meta-value { font-size: 12px; } .meta-cell:last-child .meta-value { font-size: 15px; } .party-grid, .summary { grid-template-columns: 1fr; gap: 24px; } .footer { padding-left: 24px; padding-right: 24px; } }
`;

function frame(title: string, body: string) {
  return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>${text(title)}</title><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet"><style>${css}</style></head><body>${body}<script>window.onload=()=>window.print()<\/script></body></html>`;
}

function masthead(title: string) {
  return `<div class="masthead"><div class="masthead-inner"><div><div class="brand"><div class="logo">H</div><div class="brand-name">Howlwaadag Property</div></div><div class="company"><strong>Howlwaadag Property HQ</strong>Mogadishu, Somalia<br>Professional Property Management<br>billing@howlwaadag.com</div></div><div class="title-block"><h1 class="doc-title">${text(title)}</h1><div class="document-standard">Official financial document · USD</div></div></div></div>`;
}

function footer(reference: unknown, message: string) {
  return `<footer class="footer"><div><strong>${text(message)}</strong><br>This digitally generated document is valid without a physical signature.</div><div class="verify">Generated by Howlwaadag Property<br>Document ID: ${text(reference)}</div></footer><div class="bottom-bar"></div>`;
}

function openPrint(title: string, body: string) {
  const popup = window.open("", "_blank", "width=940,height=820");
  if (!popup) return;
  popup.document.write(frame(title, body));
  popup.document.close();
}

function chargeLines(row: Row): LineItem[] {
  const period = row["billing_period"] ? formatPeriod(row["billing_period"]) : "Current billing period";
  return [
    { label: "Monthly rent", detail: period, amount: num(row["rent_amount"]) },
    { label: "Service charge", detail: `Property services · ${period}`, amount: num(row["service_charge"]) },
    { label: "Utilities", detail: `Utility consumption and services · ${period}`, amount: num(row["utilities"]) },
    { label: "Other charges", detail: String(row["notes"] ?? "Additional property charges"), amount: num(row["other_charges"]) },
  ].filter((line) => line.amount > 0);
}

function lineItemsHtml(lines: LineItem[]) {
  return lines.map((line) => `<tr><td><div class="line-title">${text(line.label)}</div>${line.detail ? `<div class="line-detail">${text(line.detail)}</div>` : ""}</td><td>1</td><td>${money(line.amount)}</td><td>${money(line.amount)}</td></tr>`).join("");
}

function commercialDocument(row: Row, tenantName: string, kind: "invoice" | "quotation") {
  const isInvoice = kind === "invoice";
  const title = isInvoice ? "Invoice" : "Quotation";
  const number = row[isInvoice ? "invoice_number" : "quotation_number"];
  const lines = chargeLines(row);
  const subtotal = lines.reduce((sum, line) => sum + line.amount, 0);
  const tax = num(row["tax"]);
  const discount = num(row["discount"]);
  const total = num(row["amount"]) || subtotal + tax - discount;
  const paid = isInvoice ? num(row["amount_paid"]) : 0;
  const balance = Math.max(0, total - paid);
  const dateLabel = isInvoice ? "Due date" : "Valid until";
  const dateValue = row[isInvoice ? "due_date" : "valid_until"];
  const status = String(row["status"] ?? (isInvoice ? "unpaid" : "draft"));
  const body = `<main class="document">${masthead(title)}
    <section class="meta-grid"><div class="meta-cell"><p class="eyebrow">${title} number</p><p class="meta-value">${text(number)}</p></div><div class="meta-cell"><p class="eyebrow">${dateLabel}</p><p class="meta-value">${formatDate(dateValue)}</p></div><div class="meta-cell"><p class="eyebrow">${isInvoice ? "Balance due" : "Quoted total"}</p><p class="meta-value ${isInvoice ? 'balance-due' : ''}">${money(isInvoice ? balance : total)}</p></div></section>
    <section class="content"><div class="party-grid"><div><p class="eyebrow">${isInvoice ? "Bill to" : "Prepared for"}</p><p class="party-name">${text(tenantName)}</p><p class="small">Tenant account<br>Howlwaadag Property managed property</p></div><div class="context"><p class="eyebrow">Document details</p><div class="context-row"><span>Billing period</span><strong>${row["billing_period"] ? formatPeriod(row["billing_period"]) : "—"}</strong></div><div class="context-row"><span>Status</span><strong>${text(status.toUpperCase())}</strong></div><div class="context-row"><span>Currency</span><strong>USD</strong></div></div></div>
    <table><thead><tr><th>Description</th><th>Qty</th><th>Rate</th><th>Total</th></tr></thead><tbody>${lineItemsHtml(lines.length ? lines : [{ label: isInvoice ? "Property charges" : "Quoted services", amount: total }])}</tbody></table>
    <div class="summary"><div class="payment-box"><p class="eyebrow">${isInvoice ? "Payment methods" : "Quotation notes"}</p><p class="small">${isInvoice ? "Pay via EVC Plus, eDahab, Zaad, Premier Bank, Salaam Somali Bank, or approved bank transfer. Include the document number as your reference." : text(row["notes"], "Prices are stated in USD and remain valid until the date shown above.")}</p>${status === "paid" ? '<span class="status">Paid</span>' : ""}</div><div><div class="total-row"><span>Subtotal</span><strong>${money(subtotal)}</strong></div>${discount > 0 ? `<div class="total-row"><span>Discount</span><strong>-${money(discount)}</strong></div>` : ""}${tax > 0 ? `<div class="total-row"><span>VAT (${num(row["vat_percent"])}%)</span><strong>${money(tax)}</strong></div>` : ""}${paid > 0 ? `<div class="total-row"><span>Payments received</span><strong>-${money(paid)}</strong></div>` : ""}<div class="total-row grand-total"><span>${isInvoice ? "Balance due" : "Total quote"}</span><span class="${isInvoice ? 'balance-due' : ''}">${money(isInvoice ? balance : total)}</span></div></div></div></section>
    ${footer(number, isInvoice ? "Thank you for your tenancy" : "We look forward to serving you")}</main>`;
  openPrint(`${title} ${String(number ?? "")}`, body);
}

export function printInvoiceDoc(row: Row, tenantName: string) {
  commercialDocument(row, tenantName, "invoice");
}

export function printQuotationDoc(row: Row, tenantName: string) {
  commercialDocument(row, tenantName, "quotation");
}

function paymentDocument(row: Row, tenantName: string, kind: "receipt" | "payment") {
  const isReceipt = kind === "receipt";
  const title = isReceipt ? "Receipt" : "Payment Receipt";
  const reference = row[isReceipt ? "receipt_number" : "reference"] ?? String(row["id"] ?? "").slice(0, 8).toUpperCase();
  const date = row[isReceipt ? "issued_on" : "paid_on"];
  const amount = num(row["amount"]);
  const body = `<main class="document">${masthead(title)}
    <section class="meta-grid"><div class="meta-cell"><p class="eyebrow">Receipt number</p><p class="meta-value">${text(reference)}</p></div><div class="meta-cell"><p class="eyebrow">Payment date</p><p class="meta-value">${formatDate(date)}</p></div><div class="meta-cell"><p class="eyebrow">Amount received</p><p class="meta-value">${money(amount)}</p></div></section>
    <section class="content"><div class="party-grid"><div><p class="eyebrow">Received from</p><p class="party-name">${text(tenantName)}</p><p class="small">Tenant account<br>Payment acknowledged in full for the amount shown</p><span class="status">Paid</span></div><div class="context"><p class="eyebrow">Payment details</p><div class="context-row"><span>Method</span><strong>${text(row["method"])}</strong></div><div class="context-row"><span>Reference</span><strong>${text(row["reference"])}</strong></div><div class="context-row"><span>Currency</span><strong>USD</strong></div></div></div>
    <table><thead><tr><th>Description</th><th>Method</th><th>Reference</th><th>Amount</th></tr></thead><tbody><tr><td><div class="line-title">Tenant payment received</div><div class="line-detail">${text(row["notes"], "Payment credited to tenant account")}</div></td><td>${text(row["method"])}</td><td>${text(row["reference"])}</td><td>${money(amount)}</td></tr></tbody></table>
    <div class="summary"><div class="payment-box"><p class="eyebrow">Official acknowledgement</p><p class="small">This receipt confirms that Howlwaadag Property recorded the payment above. Keep this document for your records.</p></div><div><div class="total-row grand-total"><span>Total received</span><span>${money(amount)}</span></div></div></div></section>
    ${footer(reference, "Payment received with thanks")}</main>`;
  openPrint(`${title} ${String(reference ?? "")}`, body);
}

export function printPayslipDoc(row: Row, employee: Row | undefined, accountName: string) {
  const employeeName = String(employee?.["full_name"] ?? "—");
  const gross = num(row["gross_pay"]);
  const tax = num(row["tax_amount"]);
  const pension = num(row["pension_amount"]);
  const insurance = num(row["insurance"]);
  const advance = num(row["advance"]);
  const other = num(row["other_deductions"]);
  const deductionsTotal = num(row["deductions"]) || tax + pension + insurance + advance + other;
  const net = num(row["net_pay"]) || gross - deductionsTotal;
  const frequency = String(row["pay_frequency"] ?? "monthly");
  const periodLabel = row["period"] ? formatPeriod(row["period"]) : "Current period";
  const slipId = `PS-${String(row["id"] ?? "").slice(0, 8).toUpperCase()}`;
  const earnings = [
    { label: "Basic salary", detail: `${frequency.charAt(0).toUpperCase() + frequency.slice(1)} pay · ${periodLabel}`, amount: gross },
  ].filter((line) => line.amount > 0);
  const notes = String(row["deduction_notes"] ?? "").trim();
  const deductionLines = [
    { label: "Income tax (PAYE)", detail: `Statutory tax · ${num(row["tax_percent"])}% of gross`, amount: tax },
    { label: "Pension contribution", detail: `Retirement savings · ${num(row["pension_percent"])}% of gross`, amount: pension },
    { label: "Health / staff insurance", detail: "Insurance premium withheld from salary", amount: insurance },
    { label: "Salary advance recovery", detail: "Repayment of advance already paid to employee", amount: advance },
    { label: "Other deductions", detail: notes || "Other agreed deductions", amount: other },
  ].filter((line) => line.amount > 0);

  const status = String(row["status"] ?? "pending");
  const body = `<main class="document">${masthead("Pay Slip")}
    <section class="meta-grid"><div class="meta-cell"><p class="eyebrow">Pay slip number</p><p class="meta-value">${text(slipId)}</p></div><div class="meta-cell"><p class="eyebrow">Pay date</p><p class="meta-value">${formatDate(row["pay_date"])}</p></div><div class="meta-cell"><p class="eyebrow">Net pay</p><p class="meta-value">${money(net)}</p></div></section>
    <section class="content"><div class="party-grid"><div><p class="eyebrow">Employee</p><p class="party-name">${text(employeeName)}</p><p class="small">${text(employee?.["job_title"], "Staff member")}<br>Pay frequency: ${text(frequency)}</p>${status === "paid" ? '<span class="status">Paid</span>' : ""}</div><div class="context"><p class="eyebrow">Payment details</p><div class="context-row"><span>Period</span><strong>${periodLabel}</strong></div><div class="context-row"><span>Method</span><strong>${text(row["payment_method"])}</strong></div><div class="context-row"><span>Paid from</span><strong>${text(accountName)}</strong></div><div class="context-row"><span>Reference</span><strong>${text(row["payment_reference"])}</strong></div></div></div>
    <table><thead><tr><th>Earnings</th><th>Qty</th><th>Rate</th><th>Total</th></tr></thead><tbody>${lineItemsHtml(earnings.length ? earnings : [{ label: "Gross pay", amount: gross }])}</tbody></table>
    ${deductionLines.length ? `<p class="eyebrow" style="margin:26px 0 0">Deductions</p><table><thead><tr><th>Description</th><th>Qty</th><th>Rate</th><th>Total</th></tr></thead><tbody>${lineItemsHtml(deductionLines)}</tbody></table>` : ""}
    <div class="summary"><div class="payment-box"><p class="eyebrow">Pay slip note</p><p class="small">This pay slip confirms the earnings and deductions for the period shown. Please contact HR with any questions about your pay.</p></div><div><div class="total-row"><span>Gross pay</span><strong>${money(gross)}</strong></div><div class="total-row"><span>Total deductions</span><strong>-${money(deductionsTotal)}</strong></div><div class="total-row grand-total"><span>Net pay</span><span>${money(net)}</span></div></div></div></section>
    ${footer(slipId, "Employee pay slip")}</main>`;
  openPrint(`Pay Slip ${employeeName}`, body);
}

export function PayslipPrintButton({ row }: { row: Row }) {
  const { data: employees = [] } = useRows("employees");
  const { data: accounts = [] } = useRows("bank_accounts");
  const employee = employees.find((e) => e["id"] === row["employee_id"]);
  const accountName = String(accounts.find((a) => a["id"] === row["bank_account_id"])?.["account_name"] ?? "—");
  return (
    <Button variant="ghost" size="icon" title="Print pay slip" aria-label="Print pay slip" onClick={() => printPayslipDoc(row, employee, accountName)}>
      <Printer className="size-4" />
    </Button>
  );
}

export function printStatementDoc(tenant: Row, invoices: Row[], payments: Row[]) {
  const tenantInvoices = invoices.filter((row) => row["tenant_id"] === tenant["id"]);
  const tenantPayments = payments.filter((row) => row["tenant_id"] === tenant["id"]);
  const entries = [
    ...tenantInvoices.map((row) => ({ date: row["due_date"] ?? row["created_at"], description: `Invoice ${row["invoice_number"] ?? ""}`, debit: num(row["amount"]), credit: 0 })),
    ...tenantPayments.map((row) => ({ date: row["paid_on"], description: `Payment · ${row["method"] ?? ""}`, debit: 0, credit: num(row["amount"]) })),
  ].sort((a, b) => String(a.date ?? "").localeCompare(String(b.date ?? "")));
  let running = 0;
  const rows = entries.map((entry) => { running += entry.debit - entry.credit; return { ...entry, balance: running }; });
  const charged = tenantInvoices.reduce((sum, row) => sum + num(row["amount"]), 0);
  const received = tenantPayments.reduce((sum, row) => sum + num(row["amount"]), 0);
  const statementId = `ST-${String(tenant["id"] ?? "").slice(0, 8).toUpperCase()}`;
  const body = `<main class="document">${masthead("Statement")}
    <section class="meta-grid"><div class="meta-cell"><p class="eyebrow">Statement number</p><p class="meta-value">${text(statementId)}</p></div><div class="meta-cell"><p class="eyebrow">Statement date</p><p class="meta-value">${formatDate(new Date().toISOString())}</p></div><div class="meta-cell"><p class="eyebrow">Closing balance</p><p class="meta-value">${money(charged - received)}</p></div></section>
    <section class="content"><div class="party-grid"><div><p class="eyebrow">Account holder</p><p class="party-name">${text(tenant["full_name"])}</p><p class="small">${text(tenant["email"], "Tenant account")}<br>${text(tenant["phone"], "Howlwaadag Property managed property")}</p></div><div class="context"><p class="eyebrow">Account summary</p><div class="context-row"><span>Total invoiced</span><strong>${money(charged)}</strong></div><div class="context-row"><span>Total received</span><strong>${money(received)}</strong></div><div class="context-row"><span>Currency</span><strong>USD</strong></div></div></div>
    <table class="statement-table"><thead><tr><th>Date</th><th>Description</th><th>Charge</th><th>Payment</th><th>Balance</th></tr></thead><tbody>${rows.length ? rows.map((entry) => `<tr><td>${formatDate(entry.date)}</td><td>${text(entry.description)}</td><td class="debit">${entry.debit ? money(entry.debit) : "—"}</td><td class="credit">${entry.credit ? money(entry.credit) : "—"}</td><td>${money(entry.balance)}</td></tr>`).join("") : '<tr><td colspan="5">No account activity recorded.</td></tr>'}</tbody></table>
    <div class="summary"><div class="payment-box"><p class="eyebrow">Statement note</p><p class="small">Please review the transactions above and contact your property manager if you need any clarification.</p></div><div><div class="total-row"><span>Total charges</span><strong>${money(charged)}</strong></div><div class="total-row"><span>Total payments</span><strong>-${money(received)}</strong></div><div class="total-row grand-total"><span>Balance due</span><span class="balance-due">${money(charged - received)}</span></div></div></div></section>
    ${footer(statementId, "Tenant account statement")}</main>`;
  openPrint(`Statement ${String(tenant["full_name"] ?? "")}`, body);
}

export function PrintDocButton({ row, kind }: { row: Row; kind: DocumentKind }) {
  const { data: tenants = [] } = useRows("tenants");
  const tenantName = String(tenants.find((tenant) => tenant["id"] === row["tenant_id"])?.["full_name"] ?? "—");
  const labels: Record<DocumentKind, string> = { invoice: "Print invoice", quotation: "Print quotation", receipt: "Print receipt", payment: "Print payment receipt" };
  return <Button variant="ghost" size="icon" title={labels[kind]} aria-label={labels[kind]} onClick={() => {
    if (kind === "invoice") printInvoiceDoc(row, tenantName);
    else if (kind === "quotation") printQuotationDoc(row, tenantName);
    else paymentDocument(row, tenantName, kind);
  }}><Printer className="size-4 text-accent-foreground" /></Button>;
}

export function StatementPrintButton({ tenant }: { tenant: Row }) {
  const { data: invoices = [] } = useRows("invoices");
  const { data: payments = [] } = useRows("payments");
  return <Button variant="outline" size="sm" onClick={() => printStatementDoc(tenant, invoices, payments)}><Printer className="mr-1 size-4" /> Statement</Button>;
}
export type StatementEntry = { date: unknown; description: string; debit: number; credit: number };

export function printLedgerStatement(options: {
  title: string;
  accountName: string;
  accountLines: string[];
  summary: { label: string; value: string }[];
  entries: StatementEntry[];
  debitLabel: string;
  creditLabel: string;
  balanceLabel: string;
  note: string;
  reference: string;
  opening?: number;
}) {
  let running = options.opening ?? 0;
  const rows = options.entries
    .slice()
    .sort((a, b) => String(a.date ?? "").localeCompare(String(b.date ?? "")))
    .map((entry) => {
      running += entry.debit - entry.credit;
      return { ...entry, balance: running };
    });
  const totalDebit = rows.reduce((sum, entry) => sum + entry.debit, 0);
  const totalCredit = rows.reduce((sum, entry) => sum + entry.credit, 0);
  const closing = (options.opening ?? 0) + totalDebit - totalCredit;
  const body = `<main class="document">${masthead(options.title)}
    <section class="meta-grid"><div class="meta-cell"><p class="eyebrow">Statement number</p><p class="meta-value">${text(options.reference)}</p></div><div class="meta-cell"><p class="eyebrow">Statement date</p><p class="meta-value">${formatDate(new Date().toISOString())}</p></div><div class="meta-cell"><p class="eyebrow">${text(options.balanceLabel)}</p><p class="meta-value">${money(closing)}</p></div></section>
    <section class="content"><div class="party-grid"><div><p class="eyebrow">Account</p><p class="party-name">${text(options.accountName)}</p><p class="small">${options.accountLines.map((line) => text(line)).join("<br>")}</p></div><div class="context"><p class="eyebrow">Summary</p>${options.summary.map((item) => `<div class="context-row"><span>${text(item.label)}</span><strong>${text(item.value)}</strong></div>`).join("")}<div class="context-row"><span>Currency</span><strong>USD</strong></div></div></div>
    <table class="statement-table"><thead><tr><th>Date</th><th>Description</th><th>${text(options.debitLabel)}</th><th>${text(options.creditLabel)}</th><th>Balance</th></tr></thead><tbody>${rows.length ? rows.map((entry) => `<tr><td>${formatDate(entry.date)}</td><td>${text(entry.description)}</td><td class="debit">${entry.debit ? money(entry.debit) : "—"}</td><td class="credit">${entry.credit ? money(entry.credit) : "—"}</td><td>${money(entry.balance)}</td></tr>`).join("") : '<tr><td colspan="5">No activity recorded.</td></tr>'}</tbody></table>
    <div class="summary"><div class="payment-box"><p class="eyebrow">Statement note</p><p class="small">${text(options.note)}</p></div><div>${options.opening ? `<div class="total-row"><span>Opening balance</span><strong>${money(options.opening)}</strong></div>` : ""}<div class="total-row"><span>Total ${text(options.debitLabel.toLowerCase())}</span><strong>${money(totalDebit)}</strong></div><div class="total-row"><span>Total ${text(options.creditLabel.toLowerCase())}</span><strong>-${money(totalCredit)}</strong></div><div class="total-row grand-total"><span>${text(options.balanceLabel)}</span><span>${money(closing)}</span></div></div></div></section>
    ${footer(options.reference, options.title)}</main>`;
  openPrint(`${options.title} · ${options.accountName}`, body);
}
