/**
 * PerCaseStatsTable — table of per-test-case statistics with row highlight.
 * @countermeasure-platform/web-components/composites/per-case-stats-table
 *
 * Mirrors the per-case stats panel the run-monitor uses. Renders one row
 * per test case with arbitrary numeric/percent columns. Highlights the
 * row whose `id === currentId`. Cells with `undefined` values render as
 * an em dash to keep alignment consistent.
 */

import * as React from 'react'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '../react/primitives/table'
import { cn } from '../react/primitives/utils'

export type PerCaseColumnFormat = 'percent' | 'number'

export interface PerCaseColumnDef {
  key: string
  label: string
  format?: PerCaseColumnFormat
}

export interface PerCaseRow {
  id: string
  /** Optional run counter — rendered alongside the case id when present. */
  runs?: number
  /** Total runs for this case (used to render `runs/runsTotal`). */
  runsTotal?: number
  /** Numeric metrics keyed by `PerCaseColumnDef.key`. */
  columns: Record<string, number | undefined>
}

export interface PerCaseStatsTableProps extends React.HTMLAttributes<HTMLDivElement> {
  rows: PerCaseRow[]
  columnDefs: PerCaseColumnDef[]
  currentId?: string
  emptyMessage?: string
}

const EM_DASH = '—'

function formatCell(value: number | undefined, format?: PerCaseColumnFormat): string {
  if (value === undefined || !Number.isFinite(value)) return EM_DASH
  switch (format) {
    case 'percent': {
      const pct = Math.abs(value) <= 1 ? value * 100 : value
      return `${pct.toFixed(1)}%`
    }
    case 'number':
      return value.toLocaleString()
    default:
      return String(value)
  }
}

export function PerCaseStatsTable({
  rows,
  columnDefs,
  currentId,
  emptyMessage = 'No test cases yet.',
  className,
  ...rest
}: PerCaseStatsTableProps) {
  if (rows.length === 0) {
    return (
      <div
        data-slot="per-case-stats-table-empty"
        className={cn(
          'rounded-md border border-border bg-muted/40 p-4 text-sm text-muted-foreground',
          className
        )}
        {...rest}
      >
        {emptyMessage}
      </div>
    )
  }

  return (
    <div data-slot="per-case-stats-table" className={cn('w-full', className)} {...rest}>
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead className="w-[40%]">Case</TableHead>
            <TableHead className="w-[15%]">Runs</TableHead>
            {columnDefs.map(col => (
              <TableHead key={col.key} className="text-right tabular-nums">
                {col.label}
              </TableHead>
            ))}
          </TableRow>
        </TableHeader>
        <TableBody>
          {rows.map(row => {
            const isCurrent = currentId !== undefined && row.id === currentId
            const runs =
              typeof row.runs === 'number'
                ? typeof row.runsTotal === 'number'
                  ? `${String(row.runs)} / ${String(row.runsTotal)}`
                  : String(row.runs)
                : EM_DASH

            return (
              <TableRow
                key={row.id}
                data-current={isCurrent ? 'true' : undefined}
                aria-current={isCurrent ? 'true' : undefined}
                className={cn(isCurrent && 'bg-accent/40 font-medium')}
              >
                <TableCell className="truncate" title={row.id}>
                  {row.id}
                </TableCell>
                <TableCell className="tabular-nums">{runs}</TableCell>
                {columnDefs.map(col => (
                  <TableCell key={col.key} className="text-right tabular-nums">
                    {formatCell(row.columns[col.key], col.format)}
                  </TableCell>
                ))}
              </TableRow>
            )
          })}
        </TableBody>
      </Table>
    </div>
  )
}
