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'

/**
 * The AI risk radar (§12).
 *
 * Six kinds of risk on one instrument, because they are genuinely different questions and
 * an operator scanning a screen needs to see at a glance which *kind* of trouble the grid
 * is in. Drawn as a polar plot: the shape of the polygon is the shape of the problem, and
 * two grids with the same headline risk score can look completely different here.
 */
export interface RadarAxis {
  key: 'emerging' | 'critical' | 'cascade' | 'regional' | 'maintenance' | 'weakSignals'
  /** 0–100. */
  value: number
  count: number
  /** The single most important item on this axis, for the list beneath. */
  lead?: { code: string; label: string; labelAr: string; probability: number; confidence: number; etaMinutes: number | null; severity: string }
}

const AXES: Array<RadarAxis['key']> = [
  'emerging',
  'critical',
  'cascade',
  'regional',
  'maintenance',
  'weakSignals',
]

const LABEL_KEY: Record<RadarAxis['key'], string> = {
  emerging: 'radar.emerging',
  critical: 'radar.criticalAssets',
  cascade: 'radar.cascadeRisks',
  regional: 'radar.regions',
  maintenance: 'radar.maintenancePriorities',
  weakSignals: 'weakSignals.title',
}

const SIZE = 260
const CENTRE = SIZE / 2
const RADIUS = CENTRE - 42

function point(index: number, value: number): [number, number] {
  const angle = (index / AXES.length) * Math.PI * 2 - Math.PI / 2
  const distance = (Math.max(0, Math.min(100, value)) / 100) * RADIUS
  return [CENTRE + Math.cos(angle) * distance, CENTRE + Math.sin(angle) * distance]
}

export async function RiskRadar({
  axes,
  className,
}: {
  axes: RadarAxis[]
  className?: string
}) {
  const { t, locale } = await getI18n()

  const byKey = new Map(axes.map((axis) => [axis.key, axis]))
  const values = AXES.map((key) => byKey.get(key)?.value ?? 0)
  const polygon = AXES.map((_, index) => point(index, values[index]).join(',')).join(' ')
  const peak = Math.max(...values)

  return (
    <Panel className={className}>
      <PanelHeader
        title={t('radar.title')}
        subtitle={t('radar.subtitle')}
        action={
          <Badge tone={peak >= 70 ? 'accent' : 'muted'}>
            {formatNumber(locale, peak, { maximumFractionDigits: 0 })}%
          </Badge>
        }
      />
      <PanelBody className="pt-0">
        <div className="flex flex-col items-center gap-4 lg:flex-row lg:items-start">
          <svg viewBox={`0 0 ${SIZE} ${SIZE}`} className="w-full max-w-[16rem] shrink-0" role="img" aria-label={t('radar.title')}>
            {/* Rings at 25 % intervals, so a reader can estimate a value without a scale. */}
            {[0.25, 0.5, 0.75, 1].map((ring) => (
              <polygon
                key={ring}
                points={AXES.map((_, index) => point(index, ring * 100).join(',')).join(' ')}
                fill="none"
                stroke="currentColor"
                className="text-border"
                strokeWidth="0.7"
              />
            ))}
            {AXES.map((_, index) => {
              const [x, y] = point(index, 100)
              return (
                <line
                  key={index}
                  x1={CENTRE}
                  y1={CENTRE}
                  x2={x}
                  y2={y}
                  stroke="currentColor"
                  className="text-border"
                  strokeWidth="0.7"
                />
              )
            })}

            <polygon points={polygon} fill="#24d07f" fillOpacity="0.18" stroke="#24d07f" strokeWidth="1.6" />

            {AXES.map((key, index) => {
              const [x, y] = point(index, values[index])
              const [lx, ly] = point(index, 118)
              return (
                <g key={key}>
                  <circle cx={x} cy={y} r={3} fill="#24d07f" />
                  <text
                    x={lx}
                    y={ly}
                    textAnchor="middle"
                    dominantBaseline="middle"
                    className="fill-current text-[8px] text-text-muted"
                  >
                    {t(LABEL_KEY[key])}
                  </text>
                </g>
              )
            })}
          </svg>

          <ul className="min-w-0 flex-1 space-y-2">
            {AXES.map((key) => {
              const axis = byKey.get(key)
              if (!axis) return null
              return (
                <li key={key} className="rounded-lg border border-border bg-surface-2/40 p-2.5">
                  <div className="flex flex-wrap items-baseline justify-between gap-2">
                    <span className="text-[11px] font-medium text-text">{t(LABEL_KEY[key])}</span>
                    <span
                      className={cn(
                        'tnum text-[11px] font-semibold',
                        axis.value >= 70 ? 'text-critical' : axis.value >= 45 ? 'text-watch' : 'text-normal',
                      )}
                    >
                      {formatNumber(locale, axis.value, { maximumFractionDigits: 0 })}%
                      <span className="ms-2 font-normal text-text-faint">
                        {formatNumber(locale, axis.count)}
                      </span>
                    </span>
                  </div>
                  {axis.lead ? (
                    <p className="tnum mt-1 text-[10px] text-text-muted">
                      <span className="font-mono text-text">{axis.lead.code}</span>
                      {' · '}
                      {t('predictions.columns.probability')}{' '}
                      {formatNumber(locale, axis.lead.probability, { maximumFractionDigits: 0 })}%
                      {' · '}
                      {t('confidence.title')}{' '}
                      {formatNumber(locale, axis.lead.confidence, { maximumFractionDigits: 0 })}%
                      {axis.lead.etaMinutes !== null
                        ? ` · ${formatNumber(locale, axis.lead.etaMinutes)} ${t('common.minutes')}`
                        : ''}
                      {' · '}
                      {t(`severity.${axis.lead.severity}`)}
                    </p>
                  ) : null}
                </li>
              )
            })}
          </ul>
        </div>
      </PanelBody>
    </Panel>
  )
}
