// #invoice/:id/print — AR Task 5 item 6. Reached from the invoice detail's
// "Print" button. App.tsx renders this with NO Sidebar/app chrome at all,
// mirroring the statement print views (reports/PrintPnl.tsx) exactly:
// print-page wrapper, a no-print toolbar (Back + "Print / Save as PDF"), and
// a paper card holding the formal document. Fetches GET
// /api/c/invoices/:id/print (server/src/invoices.ts) — a payload built
// specifically for this view (company name, customer block, lines, totals),
// so this component does no further derivation of its own.

import { useCompany } from "../lib/company";
import { useApiGet } from "../lib/useApiGet";
import { fmtMoney, isZeroMoney } from "../lib/money";
import { trimPercent } from "../lib/percent";
import { fmtDateLong } from "../lib/date";
import { ErrorBanner } from "../components/ErrorBanner";

interface PrintLine {
  description: string | null;
  quantity: string;
  unitPrice: string;
  amount: string;
}

interface InvoicePrintData {
  company: { name: string | null };
  invoice: {
    id: string;
    no: string | null;
    invoiceDate: string;
    dueDate: string;
    memo: string | null;
    documentOnly: boolean;
  };
  customer: {
    name: string;
    email: string | null;
    phone: string | null;
    address: string | null;
  };
  lines: PrintLine[];
  // Sales tax breakdown (0015) — taxRate null / taxAmount "0.0000" on every
  // untaxed invoice, in which case no tax rows print at all (invisible when
  // unused, per the design spec).
  subtotal: string;
  taxAmount: string;
  taxRate: { id: string; name: string; ratePercent: string } | null;
  total: string;
  applied: string;
  balanceDue: string;
  termsDays: number;
}

/** "1.0000" -> "1" — quantity isn't money (CLAUDE.md §2 is about monetary
 * values), so plain string trimming is fine. Mirrors InvoiceDetail.tsx's
 * identical helper. */
function fmtQuantity(q: string): string {
  if (!q.includes(".")) return q;
  return q.replace(/0+$/, "").replace(/\.$/, "");
}

export function InvoicePrint({ invoiceId }: { invoiceId: string }) {
  const { selectedCompanyId } = useCompany();
  const path = `/api/c/invoices/${invoiceId}/print`;
  const { data, loading, error, retry } = useApiGet<InvoicePrintData>(path, selectedCompanyId);

  return (
    <div className="print-page">
      <div className="print-toolbar no-print">
        <button type="button" className="back-link" onClick={() => window.history.back()}>
          ← Back
        </button>
        {data && (
          <button type="button" className="btn" onClick={() => window.print()}>
            Print / Save as PDF
          </button>
        )}
      </div>

      {error && (
        <div className="no-print print-status">
          <ErrorBanner message={error} onRetry={retry} />
        </div>
      )}
      {loading && !data && <p className="msg-inline no-print print-status">Loading&hellip;</p>}

      {data && (
        <div className="paper invoice-paper">
          <header className="statement-head">
            <div className="statement-company">{data.company.name ?? "Company"}</div>
          </header>

          <div className="invoice-print-titlebar">
            <div className="invoice-print-title">Invoice</div>
            <div className="invoice-print-no">{data.invoice.no ? `#${data.invoice.no}` : "Draft"}</div>
          </div>

          <div className="invoice-print-meta">
            <div>Invoice date: {fmtDateLong(data.invoice.invoiceDate)}</div>
            <div>Due date: {fmtDateLong(data.invoice.dueDate)}</div>
            <div>Terms: Net {data.termsDays}</div>
          </div>

          {data.invoice.documentOnly && (
            <p className="badge" style={{ margin: "12px 0" }}>
              No accounting impact — already in your books
            </p>
          )}

          <div className="invoice-print-billto">
            <div className="invoice-print-billto-label">Bill to</div>
            <div className="invoice-print-billto-name">{data.customer.name}</div>
            {data.customer.address && <div>{data.customer.address}</div>}
            {data.customer.email && <div>{data.customer.email}</div>}
            {data.customer.phone && <div>{data.customer.phone}</div>}
          </div>

          <table className="invoice-print-lines">
            <thead>
              <tr>
                <th>Description</th>
                <th className="num">Qty</th>
                <th className="num">Unit price</th>
                <th className="num">Amount</th>
              </tr>
            </thead>
            <tbody>
              {data.lines.map((l, i) => (
                <tr key={i}>
                  <td>{l.description ?? "—"}</td>
                  <td className="num">{fmtQuantity(l.quantity)}</td>
                  <td className="num">{fmtMoney(l.unitPrice)}</td>
                  <td className="num">{fmtMoney(l.amount)}</td>
                </tr>
              ))}
            </tbody>
          </table>

          {data.invoice.memo && <p className="invoice-print-memo">{data.invoice.memo}</p>}

          <div className="invoice-print-totals">
            {data.taxRate && !isZeroMoney(data.taxAmount) && (
              <>
                <div className="statement-row">
                  <span>Subtotal</span>
                  <span className="statement-row-amount">{fmtMoney(data.subtotal)}</span>
                </div>
                <div className="statement-row">
                  <span>
                    {data.taxRate.name} ({trimPercent(data.taxRate.ratePercent)}%)
                  </span>
                  <span className="statement-row-amount">{fmtMoney(data.taxAmount)}</span>
                </div>
              </>
            )}
            <div className="statement-row">
              <span>Total</span>
              <span className="statement-row-amount">{fmtMoney(data.total)}</span>
            </div>
            <div className="statement-row">
              <span>Amount paid</span>
              <span className="statement-row-amount">{fmtMoney(data.applied)}</span>
            </div>
            <div className="statement-row statement-grandtotal">
              <span>Balance due</span>
              <span className="statement-row-amount">{fmtMoney(data.balanceDue)}</span>
            </div>
          </div>

          <footer className="statement-footer">Thank you.</footer>
        </div>
      )}
    </div>
  );
}
