import { formatRelativeTime } from './format'
import { useDeckTooltip } from './DeckTooltip'
import type { CapabilityProbe } from './offload-types'

function probeLabel(probe: CapabilityProbe, showVersion?: boolean): string {
  return showVersion && probe.version ? `${probe.name} ${probe.version}` : probe.name
}

function ProbeChip(props: { probe: CapabilityProbe; showVersion?: boolean }) {
  const { probe } = props
  const checkedAtMs = probe.checkedAt ? Date.parse(probe.checkedAt) : Number.NaN
  const tooltip = useDeckTooltip(
    probe.ok
      ? `${probe.name}: ok`
      : `${probe.name}: ${probe.detail ?? 'failing, with no reason reported'}`,
    Number.isNaN(checkedAtMs)
      ? undefined
      : `checked ${formatRelativeTime(checkedAtMs)} · ${probe.checkedAt}`,
  )
  return (
    <span
      {...tooltip}
      className={`inline-flex items-center gap-1.5 rounded-[20px] border px-[9px] py-[3px] text-[11px] ${
        probe.ok ? 'border-border text-fg-muted' : 'border-danger text-danger'
      }`}
    >
      <i className={`h-1.5 w-1.5 rounded-full ${probe.ok ? 'bg-success' : 'bg-danger'}`} />
      {probeLabel(probe, props.showVersion)}
    </span>
  )
}

/**
 * A red probe always carries its reason. `reasons` renders it inline for surfaces with room;
 * every surface gets it in the tooltip.
 */
export function CapabilityProbeList(props: {
  probes: CapabilityProbe[]
  showVersion?: boolean
  reasons?: boolean
}) {
  const failing = props.probes.filter((probe) => !probe.ok)
  return (
    <div className="flex flex-col gap-1.5">
      <div className="flex flex-wrap gap-1.5">
        {props.probes.map((probe) => (
          <ProbeChip key={probe.name} probe={probe} showVersion={props.showVersion} />
        ))}
      </div>
      {props.reasons && failing.length > 0 ? (
        <ul className="flex flex-col gap-0.5 text-[11px] text-danger">
          {failing.map((probe) => (
            <li key={probe.name}>
              {probe.name}: {probe.detail ?? 'failing, with no reason reported'}
            </li>
          ))}
        </ul>
      ) : null}
    </div>
  )
}
