import { LiveDuration, formatRelativeTime, useDeckTooltip } from '@overdeck/deck-ui'
import type { JSX } from 'react'
import { isFactoryRunning, parseTimestampMs } from './factory-helpers'

export function FactoryRunTiming(props: {
  status: string | null
  startedAt: string | null
  endedAt: string | null
}): JSX.Element {
  const running = isFactoryRunning(props.status)
  const startedMs = parseTimestampMs(props.startedAt)
  const endedMs = parseTimestampMs(props.endedAt)
  const terminalMs = endedMs ?? startedMs
  const absolute = terminalMs === null ? '' : new Date(terminalMs).toISOString()
  const tooltip = useDeckTooltip(absolute, endedMs ? 'Ended' : 'Started')

  if (running) {
    return (
      <span className="tabular-nums text-fg-subtle">
        <span className="text-fg-muted">elapsed </span>
        <LiveDuration startAtMs={startedMs} />
      </span>
    )
  }

  if (terminalMs === null) return <span className="text-fg-muted">—</span>

  return (
    <time dateTime={absolute} className="tabular-nums text-fg-subtle" {...tooltip}>
      {formatRelativeTime(terminalMs)}
    </time>
  )
}
