// Print view for the balance sheet — Task 4. Reached via
// #reports/print/balance-sheet?asOf= from the on-screen tab's "Print / Save
// as PDF" button (BalanceSheet.tsx). Same no-chrome page shape as
// PrintPnl.tsx — see that file's header comment. Includes the derived
// "Accumulated profit" equity line exactly as the on-screen tab does
// (accountId is null for it — same plain-text rendering, no AccountLink,
// since there's no account to drill into for a derived total).

import { useCompany } from "../lib/company";
import { useApiGet } from "../lib/useApiGet";
import { fmtMoney } from "../lib/money";
import { fmtDateLong, todayIso } from "../lib/date";
import { ErrorBanner } from "../components/ErrorBanner";
import { StatementPrint } from "./StatementPrint";
import { StatementSection } from "./StatementSection";

interface BsRow {
  accountId: string | null;
  code: string | null;
  name: string;
  balance: string;
}

interface BsData {
  asOf: string | null;
  assets: BsRow[];
  assetsTotal: string;
  liabilities: BsRow[];
  liabilitiesTotal: string;
  equity: BsRow[];
  equityTotal: string;
  totalLiabilitiesAndEquity: string;
}

function rowKey(row: BsRow): string {
  return row.accountId ?? row.name;
}

export function PrintBalanceSheet({ asOf }: { asOf: string }) {
  const { selectedCompanyId, selectedCompany } = useCompany();
  const effectiveAsOf = asOf || todayIso();
  const path = `/api/c/reports/balance-sheet?asOf=${effectiveAsOf}`;
  const { data, loading, error, retry } = useApiGet<BsData>(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">
          <StatementPrint
            companyName={selectedCompany?.name ?? "Company"}
            title="Balance Sheet"
            periodLine={`As of ${fmtDateLong(effectiveAsOf)}`}
            generatedAt={fmtDateLong(todayIso())}
          >
            <StatementSection
              heading="Assets"
              rows={data.assets.map((r) => ({ key: rowKey(r), label: r.name, amount: r.balance }))}
              totalLabel="Total assets"
              totalAmount={data.assetsTotal}
            />
            <StatementSection
              heading="Liabilities"
              rows={data.liabilities.map((r) => ({ key: rowKey(r), label: r.name, amount: r.balance }))}
              totalLabel="Total liabilities"
              totalAmount={data.liabilitiesTotal}
            />
            <StatementSection
              heading="Equity"
              rows={data.equity.map((r) => ({ key: rowKey(r), label: r.name, amount: r.balance }))}
              totalLabel="Total equity"
              totalAmount={data.equityTotal}
            />
            <div className="statement-row statement-grandtotal">
              <span>Total liabilities and equity</span>
              <span className="statement-row-amount">{fmtMoney(data.totalLiabilitiesAndEquity)}</span>
            </div>
          </StatementPrint>
        </div>
      )}
    </div>
  );
}
