import { Badge, Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { cn } from '@/lib/cn'
import type { AgentFinding, AgentResult } from '@/lib/engine/agents'

/**
 * The agent panel (§3, §4).
 *
 * Each card is one specialist's conclusion with its evidence folded underneath. The
 * drill-down is a native `<details>` rather than a client component: the content is
 * already on the page, and shipping JavaScript to hide and show it would be a worse
 * trade on a wall display than letting the browser do it.
 */

const STATUS_TONE: Record<AgentResult['status'], string> = {
  clear: 'border-normal/30 bg-normal/8 text-normal',
  observing: 'border-info/30 bg-info/8 text-info',
  flagged: 'border-watch/35 bg-watch/10 text-watch',
  alarming: 'border-critical/35 bg-critical/10 text-critical',
}

const SEVERITY_DOT: Record<AgentFinding['severity'], string> = {
  info: 'bg-info',
  watch: 'bg-watch',
  warning: 'bg-warning',
  critical: 'bg-critical',
}

export async function AgentBoard({
  agents,
  className,
}: {
  agents: AgentResult[]
  className?: string
}) {
  const { t, locale } = await getI18n()
  const ar = locale === 'ar'

  return (
    <div className={cn('grid gap-3 lg:grid-cols-2', className)}>
      {agents.map((agent) => (
        <Panel key={agent.key} className="flex flex-col">
          <PanelHeader
            title={t(`agents.key.${agent.key}`)}
            subtitle={ar ? agent.summaryAr : agent.summary}
            action={
              <span
                className={cn(
                  'inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[11px] font-medium',
                  STATUS_TONE[agent.status],
                )}
              >
                {t(`agents.status.${agent.status}`)}
              </span>
            }
          />
          <PanelBody className="flex-1 pt-0">
            <div className="grid grid-cols-3 gap-3 border-b border-border/70 pb-3 text-[11px]">
              <div>
                <p className="text-text-faint">{t('agents.confidence')}</p>
                <p className="tnum mt-0.5 font-semibold text-text">
                  {formatNumber(locale, agent.confidence, { maximumFractionDigits: 0 })}%
                </p>
              </div>
              <div>
                <p className="text-text-faint">{t('agents.dataQuality')}</p>
                <p className="tnum mt-0.5 font-semibold text-text">
                  {formatNumber(locale, agent.dataQuality, { maximumFractionDigits: 0 })}%
                </p>
              </div>
              <div>
                <p className="text-text-faint">{t('agents.duration')}</p>
                <p className="tnum mt-0.5 font-semibold text-text">
                  {formatNumber(locale, agent.durationMs)} ms
                </p>
              </div>
            </div>

            {agent.findings.length === 0 ? (
              <p className="pt-3 text-xs text-text-muted">{t('agents.noFindings')}</p>
            ) : (
              <ul className="space-y-2.5 pt-3">
                {agent.findings.map((finding) => (
                  <li key={finding.key} className="flex items-start gap-2.5">
                    <span
                      aria-hidden
                      className={cn('mt-1.5 size-1.5 shrink-0 rounded-full', SEVERITY_DOT[finding.severity])}
                    />
                    <div className="min-w-0">
                      <p className="text-xs font-medium text-text">{ar ? finding.titleAr : finding.title}</p>
                      <p className="mt-0.5 text-[11px] leading-relaxed text-text-muted">
                        {ar ? finding.detailAr : finding.detail}
                      </p>
                    </div>
                  </li>
                ))}
              </ul>
            )}

            <details className="group mt-3 border-t border-border/70 pt-3">
              <summary className="cursor-pointer list-none text-[11px] font-medium text-brand transition-colors hover:underline">
                {t('agents.inputs')}
              </summary>
              <ul className="mt-2 flex flex-wrap gap-1.5">
                {(ar ? agent.inputsAr : agent.inputs).map((input) => (
                  <li key={input}>
                    <Badge tone="muted">{input}</Badge>
                  </li>
                ))}
              </ul>
            </details>
          </PanelBody>
        </Panel>
      ))}
    </div>
  )
}
