import { LiveDuration, StatusChip, formatDurationMs } from '@overdeck/deck-ui'
import { DataTable, withColumnResizing, withSearch, withSorting, type DataTableColumn } from '@overdeck/deck-ui'
import type { JSX } from 'react'
import type { FactoryAgentAttemptView, FactoryPhaseView } from '../../lib/factory-types'
import {
  formatAbsoluteTimestamp,
  displayStatus,
  displayText,
  formatEstimatedSpend,
  formatTokenCount,
  hostsForAttempts,
  isFactoryRunning,
  parseTimestampMs,
} from './factory-helpers'

function phaseDuration(phase: FactoryPhaseView): JSX.Element | string {
  if (phase.durationMs !== null && phase.durationMs !== undefined) return formatDurationMs(phase.durationMs)
  if (isFactoryRunning(phase.status)) {
    return <LiveDuration startAtMs={parseTimestampMs(phase.startedAt)} refreshMs={1_000} tooltipLabel="Phase started" missingNote="Phase start time was not recorded." />
  }
  return '—'
}

const PHASE_CAPABILITIES = [
  withSorting({ defaultSort: { columnId: 'seq', direction: 'asc' } }),
  withSearch({ label: 'Search phases' }),
  withColumnResizing(),
]

export function FactoryPhaseTable(props: { phases: FactoryPhaseView[]; attempts?: FactoryAgentAttemptView[] }): JSX.Element {
  const attempts = props.attempts ?? []
  const columns: DataTableColumn<FactoryPhaseView>[] = [
    { id: 'seq', header: '#', sortable: true, sortValue: (phase) => phase.seq ?? Number.MAX_SAFE_INTEGER, minWidth: 50, cell: (phase) => <span className="tabular-nums">{phase.seq ?? '—'}</span> },
    {
      id: 'name',
      header: 'Phase',
      sortable: true,
      sortValue: (phase) => phase.name ?? phase.phaseId,
      searchValue: (phase) => `${phase.name ?? ''} ${phase.phaseId} ${phase.kind ?? ''} ${phase.owner ?? ''}`,
      minWidth: 180,
      cell: (phase) => <span className="font-semibold">{displayText(phase.name, phase.phaseId)}</span>,
    },
    { id: 'kind', header: 'Kind', sortable: true, sortValue: (phase) => phase.kind ?? '', minWidth: 100, cell: (phase) => displayText(phase.kind) },
    { id: 'owner', header: 'Owner', sortable: true, sortValue: (phase) => phase.owner ?? '', minWidth: 110, cell: (phase) => displayText(phase.owner) },
    { id: 'status', header: 'Status', sortable: true, sortValue: (phase) => phase.status ?? '', minWidth: 110, cell: (phase) => <StatusChip status={displayStatus(phase.status)} /> },
    { id: 'host', header: 'Where', minWidth: 100, cell: (phase) => hostsForAttempts(attempts, phase.phaseId) },
    { id: 'started', header: 'Started', sortable: true, sortValue: (phase) => phase.startedAt ?? '', minWidth: 120, cell: (phase) => <span className="tabular-nums">{formatAbsoluteTimestamp(phase.startedAt)}</span> },
    { id: 'ended', header: 'Ended', sortable: true, sortValue: (phase) => phase.endedAt ?? '', minWidth: 120, cell: (phase) => <span className="tabular-nums">{formatAbsoluteTimestamp(phase.endedAt)}</span> },
    { id: 'duration', header: 'Duration', sortable: true, sortValue: (phase) => phase.durationMs ?? 0, minWidth: 100, cell: (phase) => <span className="tabular-nums">{phaseDuration(phase)}</span> },
    { id: 'retries', header: 'Retries', sortable: true, sortValue: (phase) => phase.retries ?? 0, minWidth: 80, cell: (phase) => <span className="tabular-nums">{phase.retries ?? '—'}</span> },
    { id: 'tokens', header: 'Tokens', sortable: true, sortValue: (phase) => phase.tokens, minWidth: 90, cell: (phase) => <span className="tabular-nums">{formatTokenCount(phase.tokens)}</span> },
    { id: 'spend', header: 'Spend', sortable: true, sortValue: (phase) => phase.spend, minWidth: 90, cell: (phase) => <span className="tabular-nums">{formatEstimatedSpend(phase.spend)}</span> },
    { id: 'error', header: 'Error', minWidth: 160, cell: (phase) => displayText(phase.error, '—') },
  ]

  return (
    <div data-testid="factory-phase-table">
      <DataTable
        caption="Factory phases"
        columns={columns}
        rows={props.phases}
        getRowId={(phase) => phase.phaseId}
        capabilities={PHASE_CAPABILITIES}
      />
    </div>
  )
}
