// Shared checkbox-rows table for picking which open invoices a payment (or
// an existing payment's unapplied credit) applies to — AR Task 6. Used by
// both ReceivePayment.tsx (new payment) and PaymentDetail.tsx's apply-credit
// mini-flow (existing credit). See openInvoiceLines.ts for the pure state
// this renders.

import { Fragment } from "react";
import { fmtDate } from "../lib/date";
import { fmtMoney } from "../lib/money";
import { lineAmountError, type OpenInvoiceLine } from "./openInvoiceLines";

export function OpenInvoiceLinesTable({
  lines,
  onToggle,
  onAmountChange,
}: {
  lines: OpenInvoiceLine[];
  onToggle: (invoiceId: string) => void;
  onAmountChange: (invoiceId: string, value: string) => void;
}) {
  if (lines.length === 0) return null;

  return (
    <table className="oi-lines-table">
      <thead>
        <tr>
          <th />
          <th>Invoice</th>
          <th>Date</th>
          <th>Due</th>
          <th className="num">Open</th>
          <th className="num">Apply</th>
        </tr>
      </thead>
      <tbody>
        {lines.map((line) => {
          const err = lineAmountError(line);
          return (
            <Fragment key={line.invoiceId}>
              <tr>
                <td>
                  <input
                    type="checkbox"
                    checked={line.checked}
                    onChange={() => onToggle(line.invoiceId)}
                    aria-label={`Apply to invoice ${line.invoiceNo ?? line.invoiceId}`}
                  />
                </td>
                <td>{line.invoiceNo ? `#${line.invoiceNo}` : "—"}</td>
                <td>{fmtDate(line.invoiceDate)}</td>
                <td className={line.overdue ? "invoice-due-overdue" : undefined}>{fmtDate(line.dueDate)}</td>
                <td className="num">{fmtMoney(line.open)}</td>
                <td className="num">
                  <input
                    className="text-input line-price"
                    type="text"
                    inputMode="decimal"
                    disabled={!line.checked}
                    value={line.amount}
                    onChange={(ev) => onAmountChange(line.invoiceId, ev.target.value)}
                  />
                </td>
              </tr>
              {err && (
                <tr>
                  <td colSpan={6} className="field-error">
                    {err}
                  </td>
                </tr>
              )}
            </Fragment>
          );
        })}
      </tbody>
    </table>
  );
}
