// Print view for the profit & loss statement — Task 4. Reached via
// #reports/print/pnl?from=&to= from the on-screen P&L tab's "Print / Save as
// PDF" button (ProfitLoss.tsx). App.tsx renders this with NO Sidebar/shell
// around it — the whole point is a page containing only the formal
// document, per the "Statement print views" spec section. Fetches the same
// /api/c/reports/pnl endpoint the on-screen tab uses (buildPath below is
// deliberately identical to ProfitLoss.tsx's) so the two views can never
// drift out of sync with each other or with the ledger.

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

interface PnlLine {
  accountId: string;
  code: string;
  name: string;
  amount: string;
}

interface PnlData {
  from: string | null;
  to: string | null;
  income: PnlLine[];
  incomeTotal: string;
  expense: PnlLine[];
  expenseTotal: string;
  net: string;
}

function buildPath(from: string, to: string): string {
  const params = new URLSearchParams();
  if (from) params.set("from", from);
  if (to) params.set("to", to);
  const qs = params.toString();
  return `/api/c/reports/pnl${qs ? `?${qs}` : ""}`;
}

/** "For the period January 1 – December 31, 2025" (same year: the "from"
 * end doesn't repeat the year), "For the period March 1, 2024 – January 31,
 * 2025" (spans years), "As of ..."-style fallbacks for an open-ended range,
 * or "All recorded activity to date" when neither bound is set (the "All
 * time" preset). */
function periodLine(from: string, to: string): string {
  if (from && to) {
    const sameYear = from.slice(0, 4) === to.slice(0, 4);
    const fromLabel = sameYear ? fmtMonthDay(from) : fmtDateLong(from);
    return `For the period ${fromLabel} – ${fmtDateLong(to)}`;
  }
  if (from) return `From ${fmtDateLong(from)} onward`;
  if (to) return `Through ${fmtDateLong(to)}`;
  return "All recorded activity to date";
}

export function PrintPnl({ from, to }: { from: string; to: string }) {
  const { selectedCompanyId, selectedCompany } = useCompany();
  const path = buildPath(from, to);
  const { data, loading, error, retry } = useApiGet<PnlData>(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="Profit & Loss Statement"
            periodLine={periodLine(from, to)}
            generatedAt={fmtDateLong(todayIso())}
          >
            <StatementSection
              heading="Income"
              rows={data.income.map((r) => ({ key: r.accountId, label: r.name, amount: r.amount }))}
              totalLabel="Total income"
              totalAmount={data.incomeTotal}
            />
            <StatementSection
              heading="Expenses"
              rows={data.expense.map((r) => ({ key: r.accountId, label: r.name, amount: r.amount }))}
              totalLabel="Total expenses"
              totalAmount={data.expenseTotal}
            />
            <div className="statement-row statement-grandtotal">
              <span>Net income</span>
              <span className="statement-row-amount">{fmtMoney(data.net)}</span>
            </div>
          </StatementPrint>
        </div>
      )}
    </div>
  );
}
