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

import { RiskOutlookChart } from '@/components/console/risk-outlook-chart'
import { LiveMapPanel } from '@/components/console/live-map-panel'
import { LiveStatCards } from '@/components/console/live-stat-cards'
import { CommandPanel } from '@/components/console/command-panel'
import { RiskRadar } from '@/components/intelligence/risk-radar'
import {
  Badge,
  DemoDataBadge,
  EmptyState,
  LinkButton,
  Meter,
  Panel,
  PanelBody,
  PanelHeader,
  PageHeader,
  StateBadge,
} from '@/components/ui/display'
import { prisma } from '@/lib/db'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n, localised } from '@/lib/i18n/server'
import { riskToState } from '@/lib/domain/enums'
import { getGridSnapshot } from '@/lib/services/grid-service'
import { getMapData } from '@/lib/services/map-service'
import { getPreventionScore, getRiskOutlook } from '@/lib/services/prevention-service'
import { getWeakLinkAnalysis } from '@/lib/services/stress-service'
import { styleForRisk } from '@/lib/ui/state-styles'
import { formatMw, formatNumber } from '@/lib/i18n/translate'
import { PermissionGate } from '@/components/console/permission-gate'

export const metadata: Metadata = { title: 'Command Center' }
export const dynamic = 'force-dynamic'

export default async function CommandCenterPage() {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()

  if (!user?.permissions.has('grid.read')) {
    return <PermissionGate />
  }

  const [snapshot, mapData, prevention, outlook, alertCount, predictionCount, recommendations] =
    await Promise.all([
      getGridSnapshot(),
      getMapData(),
      getPreventionScore(),
      getRiskOutlook(),
      prisma.alert.count({ where: { status: { in: ['new', 'acknowledged', 'in_progress'] } } }),
      prisma.prediction.count({ where: { status: 'active' } }),
      prisma.recommendation.findMany({
        where: { status: 'proposed' },
        orderBy: [{ riskReduction: 'desc' }],
        take: 5,
        include: {
          asset: { select: { code: true, name: true, nameAr: true } },
          prediction: { select: { code: true, riskScore: true, etaMinutes: true } },
        },
      }),
    ])

  const criticalAssets = snapshot.criticalAssets.slice(0, 8)

  const [livePredictions, latestAlerts, radar] = await Promise.all([
    prisma.prediction.findMany({
      where: { status: 'active' },
      orderBy: { riskScore: 'desc' },
      take: 5,
      select: {
        code: true,
        eventType: true,
        riskScore: true,
        etaMinutes: true,
        confidence: true,
        asset: { select: { code: true } },
      },
    }),
    prisma.alert.findMany({
      where: { status: { in: ['new', 'acknowledged', 'in_progress'] } },
      orderBy: { createdAt: 'desc' },
      take: 5,
      select: { code: true, title: true, titleAr: true, level: true, createdAt: true },
    }),
    getWeakLinkAnalysis({ limit: 6 }),
  ])

  // The radar's six axes, each read off something already computed rather than invented
  // for the picture (§12).
  const worstPrediction = livePredictions[0]
  const radarAxes = [
    {
      key: 'emerging' as const,
      value: Math.min(100, radar.radar.emergingRisks.length * 18),
      count: radar.radar.emergingRisks.length,
    },
    {
      key: 'critical' as const,
      value: radar.radar.criticalAssets[0]?.exposureScore ?? 0,
      count: radar.radar.criticalAssets.length,
      lead: radar.weakest
        ? {
            code: radar.weakest.code,
            label: radar.weakest.name,
            labelAr: radar.weakest.nameAr,
            probability: radar.weakest.riskScore,
            confidence: 100 - radar.weakest.recoveryDifficulty,
            etaMinutes: null,
            severity: radar.weakest.riskScore >= 70 ? 'critical' : 'high',
          }
        : undefined,
    },
    {
      key: 'cascade' as const,
      value: radar.radar.cascadeRisks[0]?.failureImpactScore ?? 0,
      count: radar.radar.cascadeRisks.length,
    },
    {
      key: 'regional' as const,
      value: radar.radar.regions[0]?.exposure ?? 0,
      count: radar.radar.regions.length,
    },
    {
      key: 'maintenance' as const,
      value:
        radar.radar.maintenancePriorities.length > 0
          ? 100 - (radar.radar.maintenancePriorities[0]?.healthScore ?? 100)
          : 0,
      count: radar.radar.maintenancePriorities.length,
    },
    {
      key: 'weakSignals' as const,
      value: worstPrediction ? worstPrediction.riskScore : 0,
      count: livePredictions.length,
      lead: worstPrediction
        ? {
            code: worstPrediction.asset.code,
            label: worstPrediction.eventType,
            labelAr: worstPrediction.eventType,
            probability: worstPrediction.riskScore,
            confidence: worstPrediction.confidence * 100,
            etaMinutes: worstPrediction.etaMinutes,
            severity: worstPrediction.riskScore >= 70 ? 'critical' : 'high',
          }
        : undefined,
    },
  ]

  return (
    <>
      <PageHeader
        title={t('commandCenter.title')}
        subtitle={t('commandCenter.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
        action={
          user.permissions.has('demo.run') ? (
            <LinkButton href="/demo" variant="outline" size="sm">
              {t('demo.start')}
            </LinkButton>
          ) : null
        }
      />

      <LiveStatCards
        staticCards={{
          activeAlerts: alertCount,
          predictedFailures: predictionCount,
          preventedFailures: prevention.potentialFailuresAvoided,
          downtimeAvoidedHours: prevention.downtimeAvoidedHours,
          co2AvoidedTons: prevention.co2AvoidedTons,
        }}
      />

      {/* The map is the hero (§8): it is the only view that answers "where" at a glance,
          and everything beside it is context for what the map is showing. */}
      <div className="mt-6 grid gap-4 xl:grid-cols-[1fr_22rem]">
        <LiveMapPanel
          assets={mapData.assets}
          regions={mapData.regions}
          showAside={false}
          height={560}
        />
        <CommandPanel
          risks={criticalAssets.slice(0, 5).map((entry) => ({
            code: entry.profile.code,
            risk: entry.risk.score,
            state: entry.state,
            loadPct: entry.sample.loadPct,
            tempC: entry.sample.tempC,
          }))}
          predictions={livePredictions.map((prediction) => ({
            code: prediction.code,
            assetCode: prediction.asset.code,
            eventType: prediction.eventType,
            riskScore: prediction.riskScore,
            etaMinutes: prediction.etaMinutes,
            confidence: prediction.confidence,
          }))}
          alerts={latestAlerts.map((alert) => ({
            code: alert.code,
            title: alert.title,
            titleAr: alert.titleAr,
            level: alert.level,
            createdAt: alert.createdAt.getTime(),
          }))}
          actions={recommendations.slice(0, 4).map((recommendation) => ({
            id: recommendation.id,
            assetCode: recommendation.asset.code,
            actionType: recommendation.actionType,
            title: recommendation.title,
            titleAr: recommendation.titleAr,
            riskReduction: recommendation.riskReduction,
          }))}
        />
      </div>

      <RiskRadar className="mt-6" axes={radarAxes} />

      <div className="mt-6 grid gap-6 xl:grid-cols-[1.35fr_1fr]">
        <Panel>
          <PanelHeader
            title={t('commandCenter.riskForecast')}
            subtitle={t('commandCenter.riskForecastNote')}
          />
          <PanelBody>
            {outlook.length > 0 ? (
              <RiskOutlookChart points={outlook} />
            ) : (
              <EmptyState title={t('common.noData')} />
            )}
          </PanelBody>
        </Panel>

        <Panel>
          <PanelHeader
            title={t('commandCenter.attentionTitle')}
            action={
              <Link href="/assets" className="text-xs font-medium text-brand hover:underline">
                {t('common.viewAll')}
              </Link>
            }
          />
          {criticalAssets.length === 0 ? (
            <EmptyState title={t('commandCenter.attentionEmpty')} />
          ) : (
            <ul className="divide-y divide-border">
              {criticalAssets.map((entry) => {
                const style = styleForRisk(entry.risk.score)
                return (
                  <li key={entry.profile.code}>
                    <Link
                      href={`/assets/${encodeURIComponent(entry.profile.code)}`}
                      className="flex items-center gap-3 px-4 py-3 transition-colors hover:bg-surface-2/50"
                    >
                      <div className="min-w-0 flex-1">
                        <div className="flex items-center gap-2">
                          <span className="font-mono text-xs text-brand">{entry.profile.code}</span>
                          <StateBadge
                            state={entry.state}
                            label={t(`states.${entry.state}`)}
                            size="sm"
                            pulse={entry.risk.score >= 75}
                          />
                        </div>
                        <p className="mt-1.5 text-[11px] text-text-muted">
                          {t('assets.columns.load')}{' '}
                          {formatNumber(locale, entry.sample.loadPct, { maximumFractionDigits: 0 })}% ·{' '}
                          {formatNumber(locale, entry.sample.tempC, { maximumFractionDigits: 0 })}
                          {t('common.units.celsius')} ·{' '}
                          {t('common.health')}{' '}
                          {formatNumber(locale, entry.sample.effectiveHealth, { maximumFractionDigits: 0 })}
                        </p>
                        <Meter
                          value={entry.risk.score}
                          state={entry.state}
                          className="mt-2"
                        />
                      </div>
                      <span className={`tnum shrink-0 text-lg font-semibold ${style.text}`}>
                        {formatNumber(locale, entry.risk.score, { maximumFractionDigits: 0 })}%
                      </span>
                    </Link>
                  </li>
                )
              })}
            </ul>
          )}
        </Panel>
      </div>

      <div className="mt-6">
        <Panel>
          <PanelHeader
            title={t('commandCenter.latestRecommendations')}
            subtitle={t('recommendations.subtitle')}
            action={
              user.permissions.has('predictions.read') ? (
                <Link href="/predictions" className="text-xs font-medium text-brand hover:underline">
                  {t('common.viewAll')}
                </Link>
              ) : null
            }
          />
          {recommendations.length === 0 ? (
            <EmptyState title={t('commandCenter.recommendationsEmpty')} />
          ) : (
            <ul className="divide-y divide-border">
              {recommendations.map((recommendation) => (
                <li
                  key={recommendation.id}
                  className="flex flex-wrap items-center gap-4 px-4 py-3.5 sm:px-5"
                >
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <Badge tone="brand">{t(`actionType.${recommendation.actionType}`)}</Badge>
                      <Link
                        href={`/assets/${encodeURIComponent(recommendation.asset.code)}`}
                        className="font-mono text-xs text-text-muted hover:text-brand"
                      >
                        {recommendation.asset.code}
                      </Link>
                    </div>
                    <p className="mt-1.5 text-sm text-text">
                      {localised(recommendation, 'title', locale)}
                    </p>
                  </div>

                  <div className="text-end">
                    <p className="text-[10px] uppercase tracking-wide text-text-faint">
                      {t('recommendations.expectedReduction')}
                    </p>
                    <p className="tnum text-lg font-semibold text-brand">
                      −{formatNumber(locale, recommendation.riskReduction, { maximumFractionDigits: 0 })}
                    </p>
                  </div>

                  {recommendation.prediction ? (
                    <div className="text-end">
                      <p className="text-[10px] uppercase tracking-wide text-text-faint">
                        {t('common.riskScore')}
                      </p>
                      <p
                        className={`tnum text-lg font-semibold ${styleForRisk(recommendation.prediction.riskScore).text}`}
                      >
                        {formatNumber(locale, recommendation.prediction.riskScore, {
                          maximumFractionDigits: 0,
                        })}
                        %
                      </p>
                    </div>
                  ) : null}
                </li>
              ))}
            </ul>
          )}
        </Panel>
      </div>

      {/* Regional strip — the same numbers the map encodes as colour, as text. */}
      <div className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
        {[...snapshot.regions]
          .sort((a, b) => b.peakRisk - a.peakRisk)
          .slice(0, 5)
          .map((region) => (
            <Panel key={region.code} className="p-4">
              <div className="flex items-start justify-between gap-2">
                <p className="truncate text-sm font-medium text-text">
                  {locale === 'ar' ? region.nameAr : region.name}
                </p>
                <StateBadge
                  state={riskToState(region.peakRisk)}
                  label={t(`states.${riskToState(region.peakRisk)}`)}
                  size="sm"
                />
              </div>
              <p className="tnum mt-3 text-xl font-semibold text-text">
                {formatMw(locale, region.loadMw)}
                <span className="ms-1 text-xs font-normal text-text-muted">
                  {t('common.units.mw')}
                </span>
              </p>
              <p className="mt-1 text-[11px] text-text-muted">
                {t('grid.columns.reserve')} {formatNumber(locale, region.reserveMarginPct, { maximumFractionDigits: 0 })}% ·{' '}
                {formatNumber(locale, region.env.tempC, { maximumFractionDigits: 0 })}
                {t('common.units.celsius')}
              </p>
              <Meter
                value={region.peakRisk}
                state={riskToState(region.peakRisk)}
                className="mt-3"
              />
            </Panel>
          ))}
      </div>
    </>
  )
}
