// Print view for the inventory valuation — Task 5 of
// docs/superpowers/plans/2026-08-03-inventory.md. Reached via
// #reports/print/inventory-valuation?asOf= from the on-screen tab's
// "Print / Save as PDF" button. Same no-chrome page shape as PrintPnl.tsx and
// PrintBalanceSheet.tsx — see PrintBalanceSheet's header — so a stock
// valuation prints to the same standard as the statements it has to agree
// with.
//
// THE TIE PRINTS TOO. A valuation report whose paper copy quietly dropped the
// line proving it agrees with the balance sheet would be exactly the document
// nobody could check later, which is the whole reason this report exists. Each
// account's tie line is on the printed page, and a non-zero difference prints
// its plain-English explanation with it.

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 { fmtQuantity, fmtUnitCost } from "../items/itemTypes";
import { StatementPrint } from "./StatementPrint";
import {
  groupByAccount, tieExplanation, tieLine, type ValuationData,
} from "./inventoryValuationData";

export function PrintInventoryValuation({ asOf }: { asOf: string }) {
  const { selectedCompanyId, selectedCompany } = useCompany();
  const effectiveAsOf = asOf || todayIso();
  const path = `/api/c/reports/inventory-valuation?asOf=${effectiveAsOf}`;
  const { data, loading, error, retry } = useApiGet<ValuationData>(path, selectedCompanyId);

  const groups = data ? groupByAccount(data) : [];

  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="Inventory Valuation"
            periodLine={`As of ${fmtDateLong(effectiveAsOf)}`}
            generatedAt={fmtDateLong(todayIso())}
          >
            {groups.map((group) => {
              const explanation = group.account ? tieExplanation(group.account) : null;
              return (
                <div
                  className="statement-section"
                  key={group.account?.accountId ?? "unattached"}
                >
                  <div className="statement-section-heading">
                    {group.account ? group.account.name : "Not in an inventory account"}
                  </div>

                  <table className="invoice-print-lines">
                    <thead>
                      <tr>
                        <th>Item</th>
                        <th className="num">On hand</th>
                        <th className="num">Average cost</th>
                        <th className="num">Value</th>
                      </tr>
                    </thead>
                    <tbody>
                      {group.items.length === 0 && (
                        <tr>
                          <td colSpan={4}>Nothing on hand in this account.</td>
                        </tr>
                      )}
                      {group.items.map((item) => (
                        <tr key={item.itemId}>
                          <td>
                            {item.name}
                            {item.sku ? ` (${item.sku})` : ""}
                          </td>
                          <td className="num">{fmtQuantity(item.qtyOnHand)}</td>
                          <td className="num">{fmtUnitCost(item.averageCost)}</td>
                          <td className="num">{fmtMoney(item.value)}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>

                  {group.account && (
                    <>
                      <p className={`tie-line${explanation ? " tie-line-bad" : ""}`}>
                        {tieLine(group.account)}
                      </p>
                      {explanation && <p className="tie-explain">{explanation}</p>}
                    </>
                  )}
                </div>
              );
            })}

            <div className="statement-row statement-grandtotal">
              <span>Total inventory</span>
              <span className="statement-row-amount">{fmtMoney(data.totalValue)}</span>
            </div>
            <p className="tie-line">
              {data.ties
                ? "Every inventory account above matches the stock recorded against it exactly. The two figures on each line are worked out separately — one from the journal entries, one from the stock movements — so they agree on the evidence, not by construction."
                : `These do not agree. The differences above add up to ${fmtMoney(data.outOfTie.replace(/^-/, ""))} across every inventory account. This report is telling you something is wrong; do not rely on the totals until it reads zero.`}
            </p>
          </StatementPrint>
        </div>
      )}
    </div>
  );
}
