import {
  CheckCircle2Icon,
  ClockIcon,
  LoaderIcon,
  TriangleAlertIcon,
} from 'lucide-react'

import { DataTimestamp } from '@/components/DataTimestamp'
import { StatusBadge } from '@/components/StatusBadge'
import type { StatusTone } from '@/components/StatusBadge'
import { formatNumber } from '@/lib/format'
import { t } from '@/lib/i18n'
import type { TranslationKey } from '@/lib/i18n'
import type { RunProps, RunState } from '@/pages/Seo/types'

const TONES: Record<RunState, { tone: StatusTone; icon: typeof ClockIcon }> = {
  QUEUED: { tone: 'neutral', icon: ClockIcon },
  RUNNING: { tone: 'neutral', icon: LoaderIcon },
  COMPLETED: { tone: 'positive', icon: CheckCircle2Icon },
  FAILED: { tone: 'critical', icon: TriangleAlertIcon },
}

/**
 * El estado de una corrida.
 *
 * Propio y no `BatchStateBadge`: los estados de este módulo son los suyos, no
 * los de la otra herramienta. Van a quedar parecidos, y aun así importarlos
 * ataría las dos verticales por un mapa que ninguna de las dos controla.
 */
export function RunStateBadge({ state }: { state: RunState }) {
  const { tone, icon } = TONES[state]
  return (
    <StatusBadge tone={tone} icon={icon}>
      {t(`seo.run.state.${state}` as TranslationKey)}
    </StatusBadge>
  )
}

/**
 * Una corrida en el historial.
 *
 * Dice **qué se pidió** y **qué llegó**, que son dos cosas distintas: un rango
 * cubierto sin filas es un rango en el que Google no reportó nada, y sin las dos
 * cifras al lado esa diferencia no se puede ver.
 */
export function RunRow({ run }: { run: RunProps }) {
  const rows = (run.summary.keyword_rows ?? 0) + (run.summary.keyword_page_rows ?? 0)

  return (
    <li className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 py-3">
      <div className="flex min-w-0 flex-col gap-1">
        <div className="flex items-center gap-2">
          <RunStateBadge state={run.state} />
          <span className="text-sm font-medium">
            {t(`seo.run.kind.${run.kind}` as TranslationKey)}
          </span>
        </div>
        <span className="text-muted-foreground text-xs tabular-nums">
          {t('seo.run.range', { start: run.requested_start, end: run.requested_end })}
        </span>
      </div>

      <div className="flex items-center gap-4 text-xs">
        {run.state === 'COMPLETED' ? (
          <span className="text-muted-foreground tabular-nums">
            {t('seo.run.rows', { rows: formatNumber(rows) })}
          </span>
        ) : null}
        {run.error_code ? (
          <span className="text-destructive">
            {t(`seo.error.${run.error_code}` as TranslationKey)}
          </span>
        ) : null}
        <DataTimestamp
          value={run.finished_at ?? run.started_at}
          emptyLabel={t('seo.run.notStarted')}
          className="text-muted-foreground"
        />
      </div>
    </li>
  )
}
