import type { Metadata } from 'next'
import Link from 'next/link'

import { PermissionGate } from '@/components/console/permission-gate'
import { StressTestRunner } from '@/components/intelligence/stress-test-runner'
import {
  Badge,
  DemoDataBadge,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StatCard,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { REGIONS } from '@/lib/data/regions'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { getWeakLinkAnalysis } from '@/lib/services/stress-service'
import type { AssetCriticality } from '@/lib/engine/criticality'
import type { Locale } from '@/lib/i18n/config'

export const metadata: Metadata = { title: 'National Risk Radar' }
export const dynamic = 'force-dynamic'

function AssetList({
  items,
  locale,
  metric,
}: {
  items: AssetCriticality[]
  locale: Locale
  metric: (item: AssetCriticality) => number
}) {
  return (
    <ul className="divide-y divide-border/60">
      {items.map((item) => (
        <li key={item.code} className="flex items-baseline justify-between gap-3 py-2">
          <div className="min-w-0">
            <Link
              href={`/assets/${encodeURIComponent(item.code)}`}
              className="font-mono text-xs text-text transition-colors hover:text-brand"
            >
              {item.code}
            </Link>
            <p className="mt-0.5 truncate text-[11px] text-text-muted">
              {locale === 'ar' ? item.nameAr : item.name}
            </p>
          </div>
          <span className="tnum shrink-0 text-xs font-medium text-text">
            {formatNumber(locale, metric(item), { maximumFractionDigits: 0 })}
          </span>
        </li>
      ))}
    </ul>
  )
}

/** National Risk Radar (§32), weakest link (§30) and the stress test (§29). */
export default async function RiskRadarPage() {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('grid.read')) return <PermissionGate />

  const analysis = await getWeakLinkAnalysis({ limit: 10 })
  const { radar, weakest } = analysis
  const canStress = user.permissions.has('stress.run')

  return (
    <>
      <PageHeader
        title={t('radar.title')}
        subtitle={t('radar.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
      />

      {weakest ? (
        <Panel glow>
          <PanelHeader
            title={t('radar.weakestLink')}
            subtitle={locale === 'ar' ? weakest.reasonAr : weakest.reason}
            action={
              <Badge tone={weakest.hasRedundancy ? 'muted' : 'accent'}>
                {weakest.hasRedundancy ? t('radar.redundant') : t('radar.notRedundant')}
              </Badge>
            }
          />
          <PanelBody className="pt-0">
            <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
              <StatCard
                label={t('radar.exposure')}
                value={formatNumber(locale, weakest.exposureScore, { maximumFractionDigits: 0 })}
                emphasis
                state={weakest.exposureScore >= 55 ? 'critical' : 'warning'}
                hint={weakest.code}
                href={`/assets/${encodeURIComponent(weakest.code)}`}
              />
              <StatCard
                label={t('radar.criticality')}
                value={formatNumber(locale, weakest.criticalityScore, { maximumFractionDigits: 0 })}
              />
              <StatCard
                label={t('radar.failureImpact')}
                value={formatNumber(locale, weakest.failureImpactScore, { maximumFractionDigits: 0 })}
              />
              <StatCard
                label={t('radar.recovery')}
                value={formatNumber(locale, weakest.recoveryDifficulty, { maximumFractionDigits: 0 })}
                hint={`${t('radar.downstream')}: ${formatNumber(locale, weakest.downstreamCustomers)}`}
              />
            </div>
          </PanelBody>
        </Panel>
      ) : null}

      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <Panel>
          <PanelHeader title={t('radar.criticalAssets')} />
          <PanelBody className="pt-0">
            <AssetList items={radar.criticalAssets} locale={locale} metric={(item) => item.exposureScore} />
          </PanelBody>
        </Panel>

        <Panel>
          <PanelHeader title={t('radar.regions')} />
          <PanelBody className="pt-0">
            <ul className="divide-y divide-border/60">
              {radar.regions.map((region) => {
                const meta = REGIONS.find((entry) => entry.code === region.code)
                return (
                  <li key={region.code} className="flex items-baseline justify-between gap-3 py-2">
                    <div>
                      <p className="text-xs text-text">
                        {meta ? (locale === 'ar' ? meta.nameAr : meta.name) : region.code}
                      </p>
                      <p className="tnum mt-0.5 text-[11px] text-text-muted">
                        {t('radar.exposure')} {formatNumber(locale, region.exposure, { maximumFractionDigits: 0 })}
                        {' · '}
                        {formatNumber(locale, region.assetsAtRisk)} {t('commandCenter.cards.assetsAtRisk')}
                      </p>
                    </div>
                    <span className="tnum text-xs font-medium text-text">
                      {formatNumber(locale, region.peakRisk, { maximumFractionDigits: 0 })}%
                    </span>
                  </li>
                )
              })}
            </ul>
          </PanelBody>
        </Panel>

        <Panel>
          <PanelHeader title={t('radar.emerging')} />
          <PanelBody className="pt-0">
            <AssetList items={radar.emergingRisks} locale={locale} metric={(item) => item.criticalityScore} />
          </PanelBody>
        </Panel>

        <Panel>
          <PanelHeader title={t('radar.cascadeRisks')} />
          <PanelBody className="pt-0">
            <AssetList
              items={radar.cascadeRisks}
              locale={locale}
              metric={(item) => item.failureImpactScore}
            />
          </PanelBody>
        </Panel>

        <Panel className="lg:col-span-2">
          <PanelHeader title={t('radar.maintenancePriorities')} />
          <PanelBody className="pt-0">
            <AssetList
              items={radar.maintenancePriorities}
              locale={locale}
              metric={(item) => item.healthScore}
            />
          </PanelBody>
        </Panel>
      </div>

      {canStress ? (
        <div className="mt-6">
          <StressTestRunner
            regions={REGIONS.map((region) => ({
              code: region.code,
              name: region.name,
              nameAr: region.nameAr,
            }))}
          />
        </div>
      ) : null}
    </>
  )
}
