import { useDeckTooltip } from './DeckTooltip'
import { resolveCiRepoGaps } from './ci-coverage'

export type RepoCiDegradation = 'budget' | 'pagination' | 'jobs'

export interface RepoCiSummary {
  repo: string
  queueComplete: boolean
  historyComplete: boolean
  trainRunsComplete: boolean
  runnersComplete: boolean
  refsComplete: boolean
  prsComplete: boolean
  trainsComplete: boolean
  prQueueDepth: number | null
  queueDepth: number | null
  runnersBusy: number | null
  runnersTotal: number | null
  landsToday: number | null
  oldestQueuedAgeH: number | null
  degraded: RepoCiDegradation[]
  pollDeferred?: boolean
}

export interface RepoCiTileProps {
  summary: RepoCiSummary
  selected: boolean
  onScope: (repo: string) => void
}

interface MetricProps {
  label: string
  value: string | null
  gapLabel: string
  danger?: boolean
}

function Metric({ label, value, gapLabel, danger }: MetricProps) {
  return (
    <span className="min-w-0">
      <span className={`block text-lg font-bold tabular-nums ${danger ? 'text-danger' : 'text-fg'}`}>
        {value ?? '—'}
      </span>
      <span className="block text-xs text-fg-muted">{value === null ? gapLabel : label}</span>
    </span>
  )
}

function formatQueuedAge(hours: number | null): string | null {
  if (hours === null) return null
  const minutes = Math.round(hours * 60)
  if (minutes < 60) return `${minutes}m`
  if (minutes % 60 === 0) return `${minutes / 60}h`
  return `${(minutes / 60).toFixed(1)}h`
}

function CoverageFootnoteLine({ gap }: { gap: ReturnType<typeof resolveCiRepoGaps>[number] }) {
  const tooltip = useDeckTooltip(gap.headline, `${gap.detail} ${gap.action}`)
  return (
    <span {...tooltip} className="block cursor-help">
      <span className="font-medium">{gap.headline}</span>
      <span className="mt-0.5 block text-fg-muted">{gap.action}</span>
    </span>
  )
}

function CoverageFootnote({ summary }: { summary: RepoCiSummary }) {
  const gaps = resolveCiRepoGaps(summary)
  if (gaps.length === 0) return null

  return (
    <span className="mt-3 block space-y-1.5 border-t border-border pt-2 text-xs text-warning">
      {gaps.map((gap) => (
        <CoverageFootnoteLine key={gap.id} gap={gap} />
      ))}
    </span>
  )
}

export function RepoCiTile({ summary, selected, onScope }: RepoCiTileProps) {
  const queuedAge = formatQueuedAge(summary.oldestQueuedAgeH)

  return (
    <button
      type="button"
      aria-pressed={selected}
      onClick={() => onScope(summary.repo)}
      className={`min-w-64 rounded-xl border bg-surface p-4 text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent ${
        selected ? 'border-accent' : 'border-border hover:border-border-strong'
      }`}
    >
      <strong className="block truncate text-sm text-fg">{summary.repo}</strong>
      <span className="mt-3 grid grid-cols-2 gap-3">
        <Metric
          label="PR queue"
          value={summary.prQueueDepth === null ? null : String(summary.prQueueDepth)}
          gapLabel="PR queue unavailable"
        />
        <Metric
          label="Actions queue"
          value={summary.queueDepth === null ? null : String(summary.queueDepth)}
          gapLabel="Actions queue unavailable"
        />
        <Metric
          label="Lands today"
          value={summary.landsToday === null ? null : String(summary.landsToday)}
          gapLabel="Lands today unavailable"
        />
        <Metric
          label="Oldest queued"
          value={queuedAge}
          gapLabel="Oldest queued age unavailable"
          danger={summary.oldestQueuedAgeH !== null && summary.oldestQueuedAgeH > 0.5}
        />
      </span>
      <CoverageFootnote summary={summary} />
    </button>
  )
}
