import { Badge, EmptyState, 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 { RootCauseResult } from '@/lib/engine/rootcause'

/**
 * Root Cause AI (§18) and the causal chain (§19).
 *
 * The chain is the point: cause, then the measured condition it produced, then the event
 * that condition is heading towards, then who is behind it. Four stages, in order, so a
 * reader can disagree with a specific link rather than with a conclusion.
 */
const STAGE_TONE: Record<string, string> = {
  cause: 'border-accent/35 bg-accent/8 text-accent',
  condition: 'border-watch/35 bg-watch/8 text-watch',
  event: 'border-critical/35 bg-critical/8 text-critical',
  impact: 'border-info/35 bg-info/8 text-info',
}

export async function RootCausePanel({
  result,
  className,
}: {
  result: RootCauseResult
  className?: string
}) {
  const { t, locale } = await getI18n()
  const ar = locale === 'ar'

  if (!result.primary) {
    return (
      <Panel className={className}>
        <PanelHeader title={t('rootCause.title')} subtitle={t('rootCause.subtitle')} />
        <EmptyState title={t('rootCause.empty')} />
      </Panel>
    )
  }

  return (
    <Panel className={className}>
      <PanelHeader
        title={t('rootCause.title')}
        subtitle={t('rootCause.subtitle')}
        action={
          <Badge tone="brand">
            {formatNumber(locale, result.confidence, { maximumFractionDigits: 0 })}%
          </Badge>
        }
      />
      <PanelBody className="pt-0">
        <div className="rounded-lg border border-accent/30 bg-accent/6 p-3">
          <p className="text-[10px] uppercase tracking-wide text-text-faint">{t('rootCause.primary')}</p>
          <p className="mt-1 text-sm font-medium text-text">
            {ar ? result.primary.labelAr : result.primary.label}
          </p>
          <p className="mt-1 text-[11px] leading-relaxed text-text-muted">
            {ar ? result.primary.evidenceAr : result.primary.evidence}
          </p>
        </div>

        <div className="mt-4">
          <p className="text-[10px] uppercase tracking-wide text-text-faint">{t('rootCause.chain')}</p>
          <ol className="mt-2 space-y-2">
            {result.chain.map((link, index) => (
              <li key={`${link.stage}-${link.key}-${index}`} className="flex items-start gap-2.5">
                <span
                  className={cn(
                    'mt-0.5 inline-flex w-20 shrink-0 justify-center rounded-full border px-2 py-0.5 text-[10px] font-medium',
                    STAGE_TONE[link.stage],
                  )}
                >
                  {t(`rootCause.stage.${link.stage}`)}
                </span>
                <div className="min-w-0">
                  <p className="text-xs font-medium text-text">{ar ? link.labelAr : link.label}</p>
                  <p className="mt-0.5 text-[11px] leading-relaxed text-text-muted">
                    {ar ? link.detailAr : link.detail}
                  </p>
                </div>
              </li>
            ))}
          </ol>
        </div>

        {result.alternatives.length > 0 ? (
          <div className="mt-4 border-t border-border/70 pt-3">
            <p className="text-[10px] uppercase tracking-wide text-text-faint">
              {t('rootCause.alternatives')}
            </p>
            <ul className="mt-2 space-y-1.5">
              {result.alternatives.map((candidate) => (
                <li key={candidate.key} className="flex items-baseline justify-between gap-3">
                  <span className="text-xs text-text-muted">{ar ? candidate.labelAr : candidate.label}</span>
                  <span className="tnum text-[11px] text-text-faint">
                    {formatNumber(locale, candidate.score, { maximumFractionDigits: 0 })}
                  </span>
                </li>
              ))}
            </ul>
          </div>
        ) : null}

        <p className="mt-4 border-t border-border/70 pt-3 text-[11px] leading-relaxed text-text-muted">
          <span className="font-medium text-text">{t('rootCause.investigation')}: </span>
          {ar ? result.recommendedInvestigationAr : result.recommendedInvestigation}
        </p>
      </PanelBody>
    </Panel>
  )
}
