import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { fmt } from "@/lib/format";
import type { ClaimDetail, ClaimDetailLineReconciliation } from "@/types";

type ServiceLinesTableProps = {
  serviceLines: ClaimDetail["serviceLines"];
  /**
   * SP7: per-line Paid + Adjustments values from the slim projection
   * embedded in the claim-detail response. Defaults to [] (renders
   * em-dash placeholders in the new columns).
   */
  lineReconciliation?: ClaimDetailLineReconciliation[];
};

function formatProcedure(line: ClaimDetail["serviceLines"][number]): string {
  const base = `${line.procedureQualifier} ${line.procedureCode}`;
  if (line.modifiers.length === 0) return base;
  return `${base} · ${line.modifiers.join(" · ")}`;
}

function formatUnits(line: ClaimDetail["serviceLines"][number]): string {
  return `${line.units ?? 0} ${line.unitType ?? ""}`.trimEnd();
}

function formatMoneyOrDash(value: string | null): string {
  if (value === null) return "—";
  const n = Number(value);
  return Number.isFinite(n) ? fmt.usdPrecise(n) : value;
}

/**
 * Service-lines table for the claim detail drawer (SP4 + SP7).
 *
 * Seven columns: line #, procedure (qualifier + code + modifiers),
 * charge (mono, prominent), units, date, paid (from 835 SVC), and
 * adjustments (sum of per-line CAS rows). Charge is the headline —
 * big mono digits with tabular-nums so columns align across rows.
 */
export function ServiceLinesTable({
  serviceLines,
  lineReconciliation = [],
}: ServiceLinesTableProps) {
  const lrByLine: Record<number, ClaimDetailLineReconciliation> = {};
  for (const lr of lineReconciliation) {
    lrByLine[lr.lineNumber] = lr;
  }

  return (
    <section className="flex flex-col gap-3 px-6 py-4">
      <h3
        data-testid="section-label"
        className="eyebrow text-[color:var(--m-ink-tertiary)]"
      >
        Service Lines ({serviceLines.length})
      </h3>

      {serviceLines.length === 0 ? (
        <p
          data-testid="service-lines-empty"
          className="text-sm text-[color:var(--m-ink-tertiary)]"
        >
          No service lines
        </p>
      ) : (
        <Table data-testid="service-lines-table">
          <TableHeader>
            <TableRow>
              <TableHead className="w-12">#</TableHead>
              <TableHead>Procedure</TableHead>
              <TableHead className="text-right">Charge</TableHead>
              <TableHead className="w-20">Units</TableHead>
              <TableHead className="w-28">Date</TableHead>
              <TableHead className="text-right" data-testid="paid-header">Paid</TableHead>
              <TableHead className="text-right" data-testid="adjustments-header">Adjustments</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {serviceLines.map((line) => {
              const lr = lrByLine[line.lineNumber];
              return (
                <TableRow
                  key={line.lineNumber}
                  data-testid="service-line-row"
                  data-line-number={line.lineNumber}
                  className="row-hover"
                >
                  <TableCell className="font-mono text-[color:var(--m-ink-secondary)]">
                    {line.lineNumber}
                  </TableCell>
                  <TableCell className="font-mono text-[color:var(--m-ink-primary)]">
                    {formatProcedure(line)}
                  </TableCell>
                  <TableCell
                    className="text-right font-mono text-base tabular-nums text-[color:var(--m-ink-primary)] font-semibold"
                    style={{ fontFamily: "var(--m-font-mono)" }}
                  >
                    {fmt.usdPrecise(line.charge)}
                  </TableCell>
                  <TableCell className="font-mono text-[color:var(--m-ink-secondary)]">
                    {formatUnits(line)}
                  </TableCell>
                  <TableCell className="font-mono text-[color:var(--m-ink-secondary)]">
                    {line.serviceDate ? fmt.date(line.serviceDate) : ""}
                  </TableCell>
                  <TableCell
                    data-testid="paid-cell"
                    className="text-right font-mono tabular-nums text-[color:var(--m-ink-primary)]"
                    style={{ fontFamily: "var(--m-font-mono)" }}
                  >
                    {formatMoneyOrDash(lr?.paid ?? null)}
                  </TableCell>
                  <TableCell
                    data-testid="adjustments-cell"
                    className="text-right font-mono tabular-nums text-[color:var(--m-ink-secondary)]"
                    style={{ fontFamily: "var(--m-font-mono)" }}
                  >
                    {formatMoneyOrDash(lr?.adjustmentsSum ?? null)}
                  </TableCell>
                </TableRow>
              );
            })}
          </TableBody>
        </Table>
      )}
    </section>
  );
}
