import { DataTable, withColumnResizing, withSearch, withSorting } from './internal/DataTable'
import { useMemo, type JSX } from 'react'
import { compareOptional } from './format'
import { planTableColumns } from './plan-table-columns'
import type { PlanTableItem } from './PlanTableRow'
import type { ResolveAction } from './resolve-action'
import { planStatusCategory } from './StatusChip'

function isActivePlanItem(item: PlanTableItem): boolean {
  if (item.needsYou) return true
  if (item.status === 'killed' || item.status === 'failed' || item.status === 'degraded') return false
  const category = planStatusCategory(item.status, item.needsYou)
  if (category === 'failed' || category === 'completed') return false
  if (item.tasksTotal > 0 && item.tasksCompleted >= item.tasksTotal) return false
  return category === 'running' || category === 'queued' || category === 'needs-you'
}

function compareActiveFirst(left: PlanTableItem, right: PlanTableItem): number {
  const leftActive = isActivePlanItem(left) ? 1 : 0
  const rightActive = isActivePlanItem(right) ? 1 : 0
  if (leftActive !== rightActive) return rightActive - leftActive
  return compareOptional(left.updatedAtMs, right.updatedAtMs, 'desc')
}

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

export function PlanTable(props: { items: PlanTableItem[]; selectedRunId: string | null; onOpen(item: PlanTableItem): void; onAbandon(item: PlanTableItem): void; onResolve(item: PlanTableItem, action: ResolveAction): void }): JSX.Element {
  const rows = useMemo(() => props.items.map((item, index) => ({ item, index })).sort((left, right) => compareActiveFirst(left.item, right.item) || left.index - right.index).map(({ item }) => item), [props.items])
  const columns = useMemo(() => planTableColumns(props), [props.selectedRunId, props.onOpen, props.onAbandon, props.onResolve])
  return <DataTable caption="Plans" columns={columns} rows={rows} getRowId={(item) => item.runId} capabilities={CAPABILITIES} />
}
