import Link from 'next/link'

import { Badge, Panel, PanelHeader } from '@/components/ui/display'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber, formatRelative } from '@/lib/i18n/translate'
import { cn } from '@/lib/cn'
import { styleForRisk } from '@/lib/ui/state-styles'

/**
 * The Command Center's context panel (§11).
 *
 * Four short lists rather than one long one, because they answer four different
 * questions an operator asks in sequence: what is worst right now, what is coming, what
 * has already been raised, and what can be done about it. Each entry links straight to
 * the surface that acts on it — a panel that tells you something and then makes you
 * navigate to find it has cost you more than it saved.
 */
export interface PanelRisk {
  code: string
  risk: number
  state: string
  loadPct: number
  tempC: number
}

export interface PanelPrediction {
  code: string
  assetCode: string
  eventType: string
  riskScore: number
  etaMinutes: number | null
  confidence: number
}

export interface PanelAlert {
  code: string
  title: string
  titleAr: string
  level: string
  createdAt: number
}

export interface PanelAction {
  id: string
  assetCode: string
  actionType: string
  title: string
  titleAr: string
  riskReduction: number
}

export async function CommandPanel({
  risks,
  predictions,
  alerts,
  actions,
  className,
}: {
  risks: PanelRisk[]
  predictions: PanelPrediction[]
  alerts: PanelAlert[]
  actions: PanelAction[]
  className?: string
}) {
  const { t, locale } = await getI18n()
  const ar = locale === 'ar'

  const Section = ({
    title,
    href,
    children,
    empty,
  }: {
    title: string
    href?: string
    children: React.ReactNode
    empty: boolean
  }) => (
    <div className="border-b border-border/60 px-4 py-3 last:border-0">
      <div className="flex items-baseline justify-between gap-2">
        <p className="type-h3 text-text-faint">{title}</p>
        {href ? (
          <Link href={href} className="text-[10px] font-medium text-brand hover:underline">
            {t('common.viewAll')}
          </Link>
        ) : null}
      </div>
      {empty ? (
        <p className="mt-2 text-[11px] text-text-faint">{t('uiState.empty')}</p>
      ) : (
        <div className="mt-2">{children}</div>
      )}
    </div>
  )

  return (
    <Panel className={cn('overflow-hidden', className)}>
      <PanelHeader title={t('radar.criticalAssets')} subtitle={t('commandCenter.subtitle')} />

      <div className="max-h-[34rem] overflow-y-auto">
        <Section title={t('radar.criticalAssets')} href="/assets" empty={risks.length === 0}>
          <ul className="space-y-1.5">
            {risks.map((risk) => (
              <li key={risk.code}>
                <Link
                  href={`/assets/${encodeURIComponent(risk.code)}`}
                  className="flex items-center justify-between gap-3 rounded-lg border border-border bg-surface-2/40 px-2.5 py-1.5 transition-colors hover:border-brand/40"
                >
                  <span className="min-w-0">
                    <span className="font-mono text-[11px] text-text">{risk.code}</span>
                    <span className="tnum ms-2 text-[10px] text-text-faint">
                      {formatNumber(locale, risk.loadPct, { maximumFractionDigits: 0 })}% ·{' '}
                      {formatNumber(locale, risk.tempC, { maximumFractionDigits: 0 })} °C
                    </span>
                  </span>
                  <span className={cn('tnum shrink-0 text-[11px] font-semibold', styleForRisk(risk.risk).text)}>
                    {formatNumber(locale, risk.risk, { maximumFractionDigits: 0 })}%
                  </span>
                </Link>
              </li>
            ))}
          </ul>
        </Section>

        <Section title={t('predictions.title')} href="/predictions" empty={predictions.length === 0}>
          <ul className="space-y-1.5">
            {predictions.map((prediction) => (
              <li key={prediction.code} className="rounded-lg border border-border bg-surface-2/40 px-2.5 py-1.5">
                <div className="flex items-baseline justify-between gap-2">
                  <span className="font-mono text-[11px] text-text">{prediction.assetCode}</span>
                  <span className="tnum text-[11px] text-watch">
                    {prediction.etaMinutes === null
                      ? '—'
                      : `${formatNumber(locale, prediction.etaMinutes)} ${t('common.minutes')}`}
                  </span>
                </div>
                <p className="mt-0.5 text-[10px] text-text-muted">
                  {t(`eventType.${prediction.eventType}`)} ·{' '}
                  <span className="tnum">
                    {t('confidence.title')}{' '}
                    {formatNumber(locale, prediction.confidence * 100, { maximumFractionDigits: 0 })}%
                  </span>
                </p>
              </li>
            ))}
          </ul>
        </Section>

        <Section title={t('alerts.title')} href="/alerts" empty={alerts.length === 0}>
          <ul className="space-y-1.5">
            {alerts.map((alert) => (
              <li key={alert.code} className="flex items-start gap-2">
                <span
                  aria-hidden
                  className={cn(
                    'mt-1.5 size-1.5 shrink-0 rounded-full',
                    alert.level === 'critical' || alert.level === 'emergency'
                      ? 'bg-critical'
                      : alert.level === 'high'
                        ? 'bg-warning'
                        : 'bg-watch',
                  )}
                />
                <div className="min-w-0">
                  <p className="truncate text-[11px] text-text">{ar ? alert.titleAr : alert.title}</p>
                  <p className="text-[10px] text-text-faint">{formatRelative(locale, alert.createdAt)}</p>
                </div>
              </li>
            ))}
          </ul>
        </Section>

        <Section
          title={t('commandCenter.latestRecommendations')}
          href="/self-healing"
          empty={actions.length === 0}
        >
          <ul className="space-y-1.5">
            {actions.map((action) => (
              <li key={action.id} className="rounded-lg border border-border bg-surface-2/40 px-2.5 py-1.5">
                <div className="flex flex-wrap items-center gap-1.5">
                  <Badge tone="brand">{t(`actionType.${action.actionType}`)}</Badge>
                  <span className="font-mono text-[10px] text-text-faint">{action.assetCode}</span>
                </div>
                <p className="mt-1 text-[11px] leading-relaxed text-text-muted">
                  {ar ? action.titleAr : action.title}
                </p>
                <p className="tnum mt-0.5 text-[10px] text-normal">
                  −{formatNumber(locale, action.riskReduction, { maximumFractionDigits: 1 })}{' '}
                  {t('common.points')}
                </p>
              </li>
            ))}
          </ul>
        </Section>
      </div>
    </Panel>
  )
}
