import {
  DeckTooltipLayer,
  formatDurationMs,
  formatRelativeTime,
  SectionCard,
  StatusChip,
  useDeckTooltip,
} from '@overdeck/deck-ui'
import { DataTable, withColumnResizing, withSearch, withSorting, type DataTableColumn } from '@platform-modules/ui-primitives'
import { useQuery } from '@tanstack/react-query'
import { fetchCollectorState } from '../../lib/collector-client'
import { adapterHealthRow } from '../../lib/health'

type HealthRow = ReturnType<typeof adapterHealthRow>

const HEALTH_COLUMNS: DataTableColumn<HealthRow>[] = [
  { id: 'system', header: 'System', sortable: true, sortValue: (row) => row.id.toLowerCase(), searchValue: (row) => row.id, minWidth: 150, cell: (row) => <span className="font-semibold text-fg">{row.id}</span> },
  { id: 'reachable', header: 'Reachable?', sortable: true, sortValue: (row) => row.reachability.toLowerCase(), searchValue: (row) => row.reachability, minWidth: 110, cell: (row) => <StatusChip status={row.reachability} /> },
  { id: 'lastSuccess', header: 'Last successful poll', sortable: true, sortValue: (row) => row.lastSuccess ?? -1, minWidth: 160, cell: (row) => <LastSuccess value={row.lastSuccess} /> },
  { id: 'latency', header: 'Poll latency', sortable: true, sortValue: (row) => row.lastPollDurationMs ?? -1, minWidth: 110, cell: (row) => <span className="block text-right tabular-nums">{row.lastPollDurationMs === null ? '—' : formatDurationMs(row.lastPollDurationMs)}</span> },
  { id: 'errors', header: 'Error streak', sortable: true, sortValue: (row) => row.consecutiveErrors, minWidth: 100, cell: (row) => <span className="block text-right tabular-nums">{row.consecutiveErrors}</span> },
  { id: 'lastError', header: 'Last error', sortable: true, sortValue: (row) => (row.lastError ?? '').toLowerCase(), searchValue: (row) => row.lastError ?? '', minWidth: 220, cell: (row) => row.lastError ?? '—' },
]

const HEALTH_CAPABILITIES = [withSorting({ defaultSort: { columnId: 'system', direction: 'asc' } }), withSearch({ label: 'Search monitored systems' }), withColumnResizing()]

function LastSuccess({ value }: { value: number | null }) {
  const iso = value === null ? null : new Date(value).toISOString()
  const tooltip = useDeckTooltip(iso ?? '')
  if (value === null) return <>—</>
  return <span {...tooltip}>{formatRelativeTime(value)}</span>
}

export function HealthContent() {
  const stateQuery = useQuery({ queryKey: ['collector-state'], queryFn: fetchCollectorState })
  if (stateQuery.isLoading) return <SectionCard title="Monitored systems">Loading collector health…</SectionCard>
  if (stateQuery.isError) {
    return (
      <SectionCard title="Monitored systems" action={{ label: 'Retry', onClick: () => void stateQuery.refetch() }}>
        Collector state unavailable.
      </SectionCard>
    )
  }

  const rows = (stateQuery.data?.adapters ?? []).map(adapterHealthRow)
  return (
    <div className="flex flex-col gap-4">
      <SectionCard title="Monitored systems">
        {rows.length === 0 ? (
          <p className="text-sm text-fg-muted">No adapters are registered with the collector.</p>
        ) : (
          <DataTable caption="Collector adapter health" columns={HEALTH_COLUMNS} rows={rows} getRowId={(row) => row.id} capabilities={HEALTH_CAPABILITIES} />
        )}
      </SectionCard>
      <SectionCard title="Coverage gap">
        Harness watchdog idle/liveness is not exposed by the control-api yet (spec A10).
      </SectionCard>
      <DeckTooltipLayer />
    </div>
  )
}
