// #purchase-order/:id/print — Task 4 of
// docs/superpowers/plans/2026-08-03-inventory.md. Reached from a purchase
// order's "Print" button. App.tsx renders this with NO Sidebar/app chrome at
// all, exactly like invoices/InvoicePrint.tsx and the statement print views:
// print-page wrapper, a no-print toolbar (Back + "Print / Save as PDF"), and a
// paper card holding the formal document.
//
// Fetches GET /api/c/purchase-orders/:id/print (server/src/purchaseOrders.ts),
// a payload built specifically for this view — company name, vendor block,
// lines, total — so this component derives nothing of its own.
//
// The document is addressed TO the vendor and says what is being asked for, so
// it carries the "Ship to" side of an invoice's "Bill to" block and a plain
// statement that it is an order rather than a bill: a vendor who mistakes one
// for the other pays nobody and gets paid by nobody.

import { useCompany } from "../lib/company";
import { useApiGet } from "../lib/useApiGet";
import { fmtMoney } from "../lib/money";
import { fmtDateLong } from "../lib/date";
import { ErrorBanner } from "../components/ErrorBanner";
// fmtUnitCost for the per-unit column — see PurchaseOrderDetail.tsx's note.
// This is the copy the vendor gets, so a sub-cent cost printed as "$0.00" is
// the worst version of the same mistake.
import { fmtQuantity, fmtUnitCost } from "../items/itemTypes";

interface PrintLine {
  description: string | null;
  itemName: string | null;
  quantity: string;
  unitCost: string;
  amount: string;
  /** null on a description-only line — nothing can observe its receipt. */
  qtyReceived: string | null;
  qtyOutstanding: string | null;
}

interface PoPrintData {
  company: { name: string | null };
  purchaseOrder: {
    id: string;
    no: string | null;
    orderDate: string;
    expectedDate: string | null;
    memo: string | null;
    status: string;
    state: string;
  };
  vendor: {
    name: string | null;
    email: string | null;
    phone: string | null;
    address: string | null;
  };
  lines: PrintLine[];
  total: string;
}

export function PurchaseOrderPrint({ poId }: { poId: string }) {
  const { selectedCompanyId } = useCompany();
  const { data, loading, error, retry } = useApiGet<PoPrintData>(
    `/api/c/purchase-orders/${poId}/print`, selectedCompanyId,
  );

  // Only a PARTLY received order changes shape. A brand-new one has nothing to
  // report, and a fully received one is a record rather than a request — both
  // print exactly as the order was placed.
  const partlyReceived = data?.purchaseOrder.state === "partial";

  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">
              {partlyReceived ? "Purchase order — still outstanding" : "Purchase order"}
            </div>
            <div className="invoice-print-no">
              {data.purchaseOrder.no ? `#${data.purchaseOrder.no}` : "Draft"}
            </div>
          </div>

          <div className="invoice-print-meta">
            <div>Order date: {fmtDateLong(data.purchaseOrder.orderDate)}</div>
            {data.purchaseOrder.expectedDate && (
              <div>Expected by: {fmtDateLong(data.purchaseOrder.expectedDate)}</div>
            )}
          </div>

          {data.purchaseOrder.state === "cancelled" && (
            <p className="badge" style={{ margin: "12px 0" }}>Cancelled</p>
          )}

          {/* F7: reprinting a partly-received order used to hand the vendor a
              document asking for the whole thing again. Say what has already
              arrived, and give the outstanding column its own place. */}
          {partlyReceived && (
            <p className="invoice-print-memo" style={{ marginTop: 12 }}>
              Part of this order has already arrived. The &ldquo;Still to come&rdquo; column is
              what we&rsquo;re waiting on — please don&rsquo;t reship what&rsquo;s already been
              received.
            </p>
          )}

          <div className="invoice-print-billto">
            <div className="invoice-print-billto-label">To</div>
            <div className="invoice-print-billto-name">{data.vendor.name ?? "Vendor"}</div>
            {data.vendor.address && <div>{data.vendor.address}</div>}
            {data.vendor.email && <div>{data.vendor.email}</div>}
            {data.vendor.phone && <div>{data.vendor.phone}</div>}
          </div>

          <table className="invoice-print-lines">
            <thead>
              <tr>
                <th>Description</th>
                <th className="num">Ordered</th>
                {partlyReceived && <th className="num">Received</th>}
                {partlyReceived && <th className="num">Still to come</th>}
                <th className="num">Unit cost</th>
                <th className="num">Amount</th>
              </tr>
            </thead>
            <tbody>
              {data.lines.map((l, i) => (
                <tr key={i}>
                  <td>{l.description ?? l.itemName ?? "—"}</td>
                  <td className="num">{fmtQuantity(l.quantity)}</td>
                  {partlyReceived && (
                    <td className="num">
                      {l.qtyReceived === null ? "—" : fmtQuantity(l.qtyReceived)}
                    </td>
                  )}
                  {partlyReceived && (
                    <td className="num">
                      {/* An em dash, not a number: a description-only line's
                          receipt is not something this system can observe. */}
                      {l.qtyOutstanding === null ? "—" : fmtQuantity(l.qtyOutstanding)}
                    </td>
                  )}
                  <td className="num">{fmtUnitCost(l.unitCost)}</td>
                  <td className="num">{fmtMoney(l.amount)}</td>
                </tr>
              ))}
            </tbody>
          </table>

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

          <div className="invoice-print-totals">
            <div className="statement-row statement-grandtotal">
              <span>Order total</span>
              <span className="statement-row-amount">{fmtMoney(data.total)}</span>
            </div>
          </div>

          <footer className="statement-footer">
            This is an order, not a bill. Please invoice us when the goods ship.
          </footer>
        </div>
      )}
    </div>
  );
}
