import {
  CheckLine as CheckIcon,
  HashtagLine as HashIcon,
  HeartbeatLine as ActivityIcon,
  StopwatchLine as TimerIcon,
} from '@mingcute/react'
import type { ReactNode } from 'react'

import { Badge } from '~/components/ui/badge'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '~/components/ui/tooltip'
import { formatShortDurationMs } from '~/lib/number-format'

export interface RunDebugCaptionViewProps {
  runId: string | null
  acceptMs: number | null
  ttfbMs: number | null
  ttftMs: number | null
  totalMs: number | null
}

/** Props-only run timing caption for assistant bubbles and Storybook fixtures. */
export function RunDebugCaptionView({
  runId,
  acceptMs,
  ttfbMs,
  ttftMs,
  totalMs,
}: RunDebugCaptionViewProps) {
  const shortRunId = runId ? `${runId.slice(0, 8)}\u2026` : 'pending'

  return (
    <TooltipProvider delayDuration={250}>
      <div className="mt-1.5 flex flex-wrap items-center gap-1.5 text-[11px] text-muted-foreground">
        <Tooltip>
          <TooltipTrigger asChild>
            <Badge
              variant="outline"
              className="h-5 max-w-full gap-1 border-border/50 bg-muted/25 px-1.5 font-mono font-normal text-[10px] text-muted-foreground tabular-nums"
            >
              <HashIcon className="size-3" aria-hidden="true" />
              <span className="truncate">{shortRunId}</span>
            </Badge>
          </TooltipTrigger>
          <TooltipContent sideOffset={6}>
            {runId ?? 'Run has not been assigned yet'}
          </TooltipContent>
        </Tooltip>
        <MetricBadge
          icon={<TimerIcon className="size-3" aria-hidden="true" />}
          label="Accept"
          value={acceptMs}
        />
        <MetricBadge
          icon={<ActivityIcon className="size-3" aria-hidden="true" />}
          label="TTFB"
          value={ttfbMs}
        />
        <MetricBadge
          icon={<TimerIcon className="size-3" aria-hidden="true" />}
          label="TTFT"
          value={ttftMs}
        />
        {totalMs !== null && (
          <MetricBadge
            icon={<CheckIcon className="size-3" aria-hidden="true" />}
            label="Done"
            value={totalMs}
          />
        )}
      </div>
    </TooltipProvider>
  )
}

function MetricBadge({
  icon,
  label,
  value,
}: {
  icon: ReactNode
  label: string
  value: number | null
}) {
  return (
    <Badge
      variant="ghost"
      className="h-5 gap-1 px-1.5 font-normal text-[10px] text-muted-foreground/80 tabular-nums"
    >
      {icon}
      <span>{label}</span>
      <span className="font-mono">
        {value === null ? '\u2026' : formatShortDurationMs(value).replaceAll(' ', '')}
      </span>
    </Badge>
  )
}
