// Shared checkbox-rows table for picking which open bills a payment (or an
// existing payment's unapplied credit) applies to — AP Task 5. Used by both
// PayBills.tsx (new payment) and BillPaymentDetail.tsx's apply-credit
// mini-flow (existing credit). Mirrors payments/OpenInvoiceLinesTable.tsx
// exactly (invoice -> bill vocabulary only). See openBillLines.ts for the
// pure state this renders.

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

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

  return (
    <table className="oi-lines-table">
      <thead>
        <tr>
          <th />
          <th>Bill</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.billId}>
              <tr>
                <td>
                  <input
                    type="checkbox"
                    checked={line.checked}
                    onChange={() => onToggle(line.billId)}
                    aria-label={`Apply to bill ${line.refNo ?? line.billId}`}
                  />
                </td>
                <td>{line.refNo ? `#${line.refNo}` : "—"}</td>
                <td>{fmtDate(line.billDate)}</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.billId, ev.target.value)}
                  />
                </td>
              </tr>
              {err && (
                <tr>
                  <td colSpan={6} className="field-error">
                    {err}
                  </td>
                </tr>
              )}
            </Fragment>
          );
        })}
      </tbody>
    </table>
  );
}
