import {
  attemptInProgress,
  elapsedTimeoutRatio,
  isAttemptAlarmed,
  shortAttemptId,
  wrapperLabel,
  type AttemptRecord,
} from './attempt-record'
import { StaleBadge, StatusChip, VerdictBadge, type Verdict } from '@overdeck/deck-ui'

function verdictForAttempt(attempt: AttemptRecord): Verdict {
  if (attempt.valid === true) return 'works'
  if (attempt.valid === false) return 'broken'
  const verdict = attempt.verdict?.trim().toLowerCase()
  if (['pass', 'passed', 'works', 'valid', 'succeeded'].includes(verdict ?? '')) return 'works'
  if (['fail', 'failed', 'broken', 'invalid', 'error'].includes(verdict ?? '')) return 'broken'
  if (verdict === 'missing') return 'missing'
  return 'unverified'
}

export function AttemptTimeline(props: {
  attempts: AttemptRecord[]
  nowMs?: number | null
  selectedAttemptId?: string | null
  onAttemptClick?(attemptId: string): void
}) {
  const nowMs = props.nowMs ?? Date.now()

  return (
    <section aria-labelledby="attempt-timeline-title" className="min-w-0 rounded-xl border border-border bg-surface">
      <header className="border-b border-border px-5 py-4">
        <h2 id="attempt-timeline-title" className="text-base font-semibold text-fg">
          Attempt timeline
        </h2>
        <p className="mt-0.5 text-xs text-fg-muted">one entry per dispatch · journal order</p>
      </header>

      {props.attempts.length === 0 ? (
        <p className="px-5 py-6 text-sm text-fg-muted">No attempts recorded yet.</p>
      ) : (
        <ol className="divide-y divide-border">
          {props.attempts.map((attempt, index) => {
            const alarmed = isAttemptAlarmed(attempt, nowMs)
            const inProgress = attemptInProgress(attempt)
            const selected = props.selectedAttemptId === attempt.attemptId
            const ratio = elapsedTimeoutRatio(attempt)

            return (
              <li key={attempt.attemptId}>
                <button
                  type="button"
                  data-testid={`attempt-entry-${attempt.attemptId}`}
                  data-attempt-index={index}
                  data-alarmed={alarmed ? 'true' : 'false'}
                  aria-pressed={selected}
                  onClick={() => props.onAttemptClick?.(attempt.attemptId)}
                  className={[
                    'grid w-full min-h-12 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-4 gap-y-1 px-5 py-3 text-left transition-colors',
                    selected ? 'bg-surface-raised' : 'hover:bg-surface-raised/60',
                    alarmed ? 'border-l-4 border-l-warning bg-warning/5' : 'border-l-4 border-l-transparent',
                  ].join(' ')}
                >
                  <span className="font-mono text-xs font-semibold text-fg" title={attempt.attemptId}>
                    {shortAttemptId(attempt.attemptId)}
                  </span>
                  <span className="min-w-0 truncate text-xs text-fg-muted">
                    {[attempt.model, wrapperLabel(attempt.wrapper)].filter(Boolean).join(' · ')}
                  </span>
                  <span className="flex flex-wrap items-center justify-end gap-2 text-xs">
                    {alarmed && (
                      <span data-testid={`attempt-stalled-${attempt.attemptId}`}>
                        <StaleBadge
                          status={{
                            id: attempt.attemptId,
                            interval: 60_000,
                            lastSuccess: attempt.liveness ? Date.parse(attempt.liveness.lastSignalAt) : undefined,
                            stale: true,
                          }}
                          now={nowMs}
                        />
                      </span>
                    )}
                    {inProgress ? <StatusChip status="running" /> : <VerdictBadge verdict={verdictForAttempt(attempt)} />}
                    {ratio && (
                      <span className="font-mono text-fg-subtle" data-testid={`attempt-ratio-${attempt.attemptId}`}>
                        {ratio}
                      </span>
                    )}
                  </span>
                </button>
              </li>
            )
          })}
        </ol>
      )}
    </section>
  )
}
