import {
  DataTable,
  withColumnResizing,
  withPagination,
  withSearch,
  withSorting,
  type DataTableColumn,
} from './internal/DataTable'
import { ratioPercent } from './format'

export interface LimitsAccountRow {
  slug: string
  provider?: 'codex' | 'claude'
  label?: string
  percent: number | null
  status: string
  capEtaMinutes: number | null
  spend?: { amount: number | null; display: string | null } | null
}

export interface LimitsAccountsTableProps {
  accounts: readonly LimitsAccountRow[]
  /** Overview widget: sort only. Limits page: full search/resize/pagination. */
  compact?: boolean
}

function usageSummary(row: LimitsAccountRow): string {
  if (row.percent === null) {
    return row.status !== 'ok' ? row.status : '—'
  }
  if (row.capEtaMinutes === null) return `${Math.round(row.percent)}%`
  return `${Math.round(row.percent)}% · ~${Math.round(row.capEtaMinutes)}m left`
}

function usageTier(row: LimitsAccountRow): 'crit' | 'warn' | 'ok' {
  const broken = row.percent === null && row.status !== 'ok'
  if (broken || (row.percent ?? 0) >= 90) return 'crit'
  if ((row.percent ?? 0) >= 75) return 'warn'
  return 'ok'
}

const USAGE_TEXT: Record<'crit' | 'warn' | 'ok', string> = {
  crit: 'text-danger',
  warn: 'text-warning',
  ok: 'text-success',
}

const USAGE_FILL: Record<'crit' | 'warn' | 'ok', string> = {
  crit: 'bg-danger',
  warn: 'bg-warning',
  ok: 'bg-success',
}

const COLUMNS: Array<DataTableColumn<LimitsAccountRow>> = [
  {
    id: 'account',
    header: 'Account',
    sortable: true,
    resizable: true,
    sortValue: (row) => row.label ?? row.slug,
    searchValue: (row) => `${row.label ?? row.slug} ${row.provider ?? ''}`,
    cell: (row) => <span className="font-medium">{row.label ?? row.slug}</span>,
    minWidth: 140,
  },
  {
    id: 'usage',
    header: 'Usage',
    sortable: true,
    resizable: true,
    sortValue: (row) => row.percent ?? -1,
    searchValue: (row) => usageSummary(row),
    cell: (row) => {
      const tier = usageTier(row)
      return (
        <div className="min-w-[8rem]">
          <div className={`mb-1 text-right text-[12px] tabular-nums ${USAGE_TEXT[tier]}`}>
            {usageSummary(row)}
          </div>
          <div className="h-1.5 rounded-[3px] bg-[var(--mod-color-track)]">
            <i
              className={`block h-full rounded-[3px] ${USAGE_FILL[tier]}`}
              style={{ width: `${ratioPercent(row.percent ?? 0, 100)}%` }}
            />
          </div>
        </div>
      )
    },
    minWidth: 120,
  },
  {
    id: 'spend',
    header: 'Spend',
    sortable: true,
    resizable: true,
    sortValue: (row) => row.spend?.amount ?? -1,
    searchValue: (row) => row.spend?.display ?? '',
    cell: (row) => (
      <span className="tabular-nums text-fg-muted">{row.spend?.display ?? '—'}</span>
    ),
    minWidth: 88,
  },
]

export function LimitsAccountsTable({ accounts, compact = false }: LimitsAccountsTableProps) {
  const capabilities = compact
    ? [withSorting()]
    : [
        withSorting(),
        withSearch({ label: 'Filter accounts' }),
        withColumnResizing(),
        withPagination({ pageSize: 20 }),
      ]

  return (
    <DataTable
      caption="Account limits and spend"
      columns={COLUMNS}
      rows={accounts}
      getRowId={(row) => row.slug}
      capabilities={capabilities}
      emptyState={<span className="text-fg-muted">No accounts in collector state.</span>}
    />
  )
}
