import type { JSX } from 'react'
import { useDeckTooltip } from './DeckTooltip'
import { formatRelativeTime } from './format'
import { safeHttpUrl } from './safe-url'
import { StatusChip } from './StatusChip'

export function PlanRunListRow(props: {
  title: string
  status: string
  seq?: number
  tasksCompleted: number
  tasksTotal: number
  updatedAtMs: number
  activeAgents: number
  selected: boolean
  onSelect(): void
  href: string | undefined
}): JSX.Element {
  const hasUpdatedAt = Number.isFinite(props.updatedAtMs)
  const absoluteUpdatedAt = hasUpdatedAt ? new Date(props.updatedAtMs).toISOString() : ''
  const updatedTooltip = useDeckTooltip(absoluteUpdatedAt, 'Last recorded activity')

  return (
    <article
      className={`grid shrink-0 grid-cols-[minmax(0,1fr)_auto] items-stretch overflow-hidden rounded-lg border bg-surface transition-colors duration-200 ease-out ${
        props.selected ? 'border-accent bg-accent/5' : 'border-border hover:border-border-strong'
      }`}
    >
      <button
        type="button"
        aria-label={`Select ${props.title}`}
        aria-pressed={props.selected}
        onClick={props.onSelect}
        className="min-h-20 min-w-0 px-4 py-3 text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-accent"
      >
        <span className="flex min-w-0 items-center gap-2">
          <strong className="truncate text-sm text-fg">{props.title}</strong>
          <StatusChip status={props.status} />
        </span>
        <span className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs tabular-nums text-fg-subtle">
          {props.seq !== undefined && <span>run #{props.seq}</span>}
          <span>
            {props.tasksCompleted}/{props.tasksTotal} tasks
          </span>
          {hasUpdatedAt && (
            <time dateTime={absoluteUpdatedAt} {...updatedTooltip}>
              {formatRelativeTime(props.updatedAtMs)}
            </time>
          )}
          {props.activeAgents > 0 && (
            <span>
              {props.activeAgents} active {props.activeAgents === 1 ? 'agent' : 'agents'}
            </span>
          )}
        </span>
      </button>
      <a
        href={safeHttpUrl(props.href)}
        className="inline-flex min-h-11 min-w-14 items-center justify-center border-l border-border px-3 text-xs font-semibold text-accent no-underline hover:bg-surface-raised focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-accent"
      >
        Open
      </a>
    </article>
  )
}
