import { DataTable, withColumnResizing, withSearch, withSorting, type DataTableColumn } from './internal/DataTable'
import { StatusDot, type StatusDotColor } from './internal/StatusDot'
import type { ForensicsRun } from './forensics-types'
import { formatDurationMs } from './format'

export interface RunTableProps {
  runs: ForensicsRun[]
}

function outcomeDot(outcome: string): StatusDotColor {
  if (outcome === 'done') return 'green'
  if (outcome === 'crash') return 'red'
  return 'amber'
}

const COLUMNS: DataTableColumn<ForensicsRun>[] = [
  { id: 'run', header: 'Run', minWidth: 70, sortable: true, sortValue: (run) => run.index, searchValue: (run) => `#${run.index}`, cell: (run) => `#${run.index}` },
  { id: 'duration', header: 'Duration', minWidth: 90, sortable: true, sortValue: (run) => run.durationMs, cell: (run) => <span className="tabular-nums">{formatDurationMs(run.durationMs)}</span> },
  { id: 'outcome', header: 'Outcome', minWidth: 100, sortable: true, sortValue: (run) => run.outcome.toLowerCase(), searchValue: (run) => run.outcome, cell: (run) => <StatusDot color={outcomeDot(run.outcome)} label={run.outcome} /> },
  { id: 'landed', header: 'Landed', minWidth: 80, sortable: true, sortValue: (run) => run.landed, cell: (run) => <span className="tabular-nums">{run.landed}</span> },
  { id: 'quarantined', header: 'Quarantined', minWidth: 100, sortable: true, sortValue: (run) => run.quarantined, cell: (run) => <span className="tabular-nums">{run.quarantined}</span> },
  { id: 'skipped', header: 'Skipped', minWidth: 80, sortable: true, sortValue: (run) => run.skipped, cell: (run) => <span className="tabular-nums">{run.skipped}</span> },
  { id: 'gate0', header: 'gate0 fails', minWidth: 90, sortable: true, sortValue: (run) => run.gate0Fails, cell: (run) => <span className="tabular-nums">{run.gate0Fails}</span> },
  { id: 'fixer', header: 'Fixer attempts', minWidth: 110, sortable: true, sortValue: (run) => run.fixerAttempts, cell: (run) => <span className="tabular-nums">{run.fixerAttempts}</span> },
]

const CAPABILITIES = [withSorting(), withSearch({ label: 'Search runs' }), withColumnResizing()]

/** Tabular companion to RunLanes — the same `runs[]` payload, reusing BotTable's table/status-dot style. */
export function RunTable({ runs }: RunTableProps) {
  return (
    <DataTable caption="Runs" columns={COLUMNS} rows={runs} getRowId={(run) => `${run.index}-${run.startTs}`} capabilities={CAPABILITIES} />
  )
}
