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

import { PermissionGate } from '@/components/console/permission-gate'
import { RiskGauge } from '@/components/charts/risk-gauge'
import {
  Badge,
  DemoDataBadge,
  KeyValue,
  Meter,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StatCard,
  StateBadge,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { riskToState } from '@/lib/domain/enums'
import { getI18n, localised } from '@/lib/i18n/server'
import { formatMw, formatNumber } from '@/lib/i18n/translate'
import { getGridSnapshot } from '@/lib/services/grid-service'
import { getPreventionScore } from '@/lib/services/prevention-service'
import { stabilityBand } from '@/lib/engine/risk'

export const metadata: Metadata = { title: 'Executive dashboard' }
export const dynamic = 'force-dynamic'

/**
 * The executive view (§21).
 *
 * Deliberately not the engineer's screen with bigger fonts: no per-asset telemetry, no
 * electrical detail. It answers "how exposed are we, what did we avoid, and what needs a
 * decision" — and every projected figure carries its "demo estimate" label, because
 * presenting a modelled number to a decision-maker without that label would be the
 * single most misleading thing this build could do.
 */
export default async function ExecutivePage() {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()

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

  const [snapshot, prevention, models, topRecommendations, activePredictions, openAlerts] =
    await Promise.all([
      getGridSnapshot(),
      getPreventionScore(),
      prisma.modelVersion.findMany({ where: { status: 'active' } }),
      prisma.recommendation.findMany({
        where: { status: { in: ['proposed', 'simulated'] } },
        orderBy: { riskReduction: 'desc' },
        take: 5,
        include: { asset: { select: { code: true, region: { select: { name: true, nameAr: true } } } } },
      }),
      prisma.prediction.count({ where: { status: 'active' } }),
      prisma.alert.count({ where: { status: { in: ['new', 'acknowledged', 'in_progress'] } } }),
    ])

  const band = stabilityBand(snapshot.stabilityIndex)
  const regionsAtRisk = snapshot.regions.filter((region) => region.peakRisk >= 55)
  const averageAccuracy = models.length
    ? models.reduce((sum, model) => sum + model.accuracy, 0) / models.length
    : 0

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

      <div className="grid gap-6 xl:grid-cols-[300px_1fr]">
        <Panel className="flex flex-col items-center p-6">
          <p className="mb-3 text-xs font-medium text-text-muted">{t('executive.nationalHealth')}</p>
          <RiskGauge
            value={snapshot.stabilityIndex}
            label={t(`stabilityBand.${band}`)}
            showBands={false}
          />
          <dl className="mt-5 w-full space-y-1 border-t border-border pt-5">
            <KeyValue
              label={t('commandCenter.cards.totalLoad')}
              value={`${formatMw(locale, snapshot.totalLoadMw)} ${t('common.units.mw')}`}
              mono
            />
            <KeyValue
              label={t('commandCenter.reserveMargin')}
              value={`${formatNumber(locale, snapshot.reserveMarginPct, { maximumFractionDigits: 1 })}%`}
              mono
            />
            <KeyValue
              label={t('executive.renewableContribution')}
              value={`${formatNumber(locale, snapshot.renewableSharePct, { maximumFractionDigits: 1 })}%`}
              mono
            />
          </dl>
        </Panel>

        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          <StatCard
            label={t('executive.criticalRisks')}
            value={formatNumber(locale, snapshot.criticalAssets.filter((a) => a.risk.score >= 75).length)}
            state={snapshot.criticalAssets.some((a) => a.risk.score >= 75) ? 'critical' : 'normal'}
          />
          <StatCard
            label={t('executive.predictedEvents')}
            value={formatNumber(locale, activePredictions)}
            state={activePredictions > 0 ? 'warning' : 'normal'}
          />
          <StatCard
            label={t('executive.preventedEvents')}
            value={formatNumber(locale, prevention.potentialFailuresAvoided)}
            state="normal"
            hint={t('common.demoEstimate')}
          />
          <StatCard
            label={t('executive.regionsAtRisk')}
            value={formatNumber(locale, regionsAtRisk.length)}
            hint={`${snapshot.regions.length} ${t('common.regions').toLowerCase()}`}
            state={regionsAtRisk.length > 0 ? 'warning' : 'normal'}
          />
          <StatCard
            label={t('commandCenter.cards.activeAlerts')}
            value={formatNumber(locale, openAlerts)}
            href="/alerts"
          />
          <StatCard
            label={t('executive.aiPerformance')}
            value={formatNumber(locale, averageAccuracy * 100, { maximumFractionDigits: 1 })}
            unit="%"
            hint={`${models.length} ${t('models.title').toLowerCase()}`}
            href="/models"
          />
          <StatCard
            label={t('executive.metrics.downtimeAvoided')}
            value={formatNumber(locale, prevention.downtimeAvoidedHours, { maximumFractionDigits: 0 })}
            unit={t('common.units.hours')}
            hint={t('common.demoEstimate')}
          />
          <StatCard
            label={t('executive.metrics.customersProtected')}
            value={formatNumber(locale, prevention.customersProtected)}
            hint={t('common.demoEstimate')}
          />
          <StatCard
            label={t('executive.financialImpact')}
            value={formatNumber(locale, prevention.economicImpactSar / 1_000_000, {
              maximumFractionDigits: 1,
            })}
            unit={`M ${t('common.units.sar')}`}
            hint={t('common.demoEstimate')}
          />
        </div>
      </div>

      <Panel className="mt-6">
        <PanelHeader
          title={t('executive.preventionScore')}
          subtitle={t('executive.preventionScoreNote')}
          action={<DemoDataBadge label={t('common.demoEstimate')} />}
        />
        <PanelBody>
          <dl className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
            <Metric
              label={t('executive.metrics.predictedRisks')}
              value={formatNumber(locale, prevention.predictedRisks)}
            />
            <Metric
              label={t('executive.metrics.recommendations')}
              value={formatNumber(locale, prevention.recommendations)}
            />
            <Metric
              label={t('executive.metrics.simulations')}
              value={formatNumber(locale, prevention.simulations)}
            />
            <Metric
              label={t('executive.metrics.avoided')}
              value={formatNumber(locale, prevention.potentialFailuresAvoided)}
              accent
            />
            <Metric
              label={t('executive.metrics.downtimeAvoided')}
              value={`${formatNumber(locale, prevention.downtimeAvoidedHours, { maximumFractionDigits: 0 })} ${t('common.units.hours')}`}
              accent
            />
            <Metric
              label={t('commandCenter.cards.co2Avoided')}
              value={`${formatNumber(locale, prevention.co2AvoidedTons, { maximumFractionDigits: 0 })} ${t('common.units.tons')}`}
              accent
            />
          </dl>

          <p className="mt-5 rounded-lg border border-watch/25 bg-watch/8 px-4 py-3 text-xs leading-relaxed text-watch">
            {t('executive.disclaimer')}
          </p>
        </PanelBody>
      </Panel>

      <div className="mt-6 grid gap-6 xl:grid-cols-2">
        <Panel>
          <PanelHeader
            title={t('executive.regionsAtRisk')}
            action={
              <Link href="/grid" className="text-xs font-medium text-brand hover:underline">
                {t('common.viewAll')}
              </Link>
            }
          />
          <PanelBody className="space-y-2.5">
            {[...snapshot.regions]
              .sort((a, b) => b.peakRisk - a.peakRisk)
              .slice(0, 6)
              .map((region) => (
                <div
                  key={region.code}
                  className="flex flex-wrap items-center gap-3 rounded-lg border border-border bg-surface-2/40 px-3.5 py-3"
                >
                  <span className="min-w-28 text-sm text-text">
                    {locale === 'ar' ? region.nameAr : region.name}
                  </span>
                  <Meter
                    value={region.peakRisk}
                    state={riskToState(region.peakRisk)}
                    className="min-w-24 flex-1"
                  />
                  <span className="tnum text-xs text-text-muted">
                    {formatMw(locale, region.loadMw)} {t('common.units.mw')}
                  </span>
                  <StateBadge
                    state={region.state}
                    label={t(`states.${region.state}`)}
                    size="sm"
                  />
                </div>
              ))}
          </PanelBody>
        </Panel>

        <Panel>
          <PanelHeader
            title={t('executive.topRecommendations')}
            action={
              user.permissions.has('predictions.read') ? (
                <Link href="/predictions" className="text-xs font-medium text-brand hover:underline">
                  {t('common.viewAll')}
                </Link>
              ) : null
            }
          />
          {topRecommendations.length === 0 ? (
            <PanelBody>
              <p className="text-sm text-text-muted">{t('recommendations.empty')}</p>
            </PanelBody>
          ) : (
            <ul className="divide-y divide-border">
              {topRecommendations.map((recommendation) => (
                <li key={recommendation.id} className="flex items-center gap-4 px-4 py-3 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>
                      <span className="font-mono text-[11px] text-text-muted">
                        {recommendation.asset.code}
                      </span>
                      <span className="text-[11px] text-text-faint">
                        {localised(recommendation.asset.region, 'name', locale)}
                      </span>
                    </div>
                    <p className="mt-1.5 truncate text-sm text-text">
                      {localised(recommendation, 'title', locale)}
                    </p>
                  </div>
                  <span className="tnum shrink-0 text-lg font-semibold text-brand">
                    −{formatNumber(locale, recommendation.riskReduction, { maximumFractionDigits: 0 })}
                  </span>
                </li>
              ))}
            </ul>
          )}
        </Panel>
      </div>
    </>
  )
}

function Metric({
  label,
  value,
  accent = false,
}: {
  label: string
  value: string
  accent?: boolean
}) {
  return (
    <div className="rounded-lg border border-border bg-surface-2/40 px-4 py-3.5">
      <dt className="text-[10px] uppercase tracking-wide text-text-faint">{label}</dt>
      <dd className={`tnum mt-1.5 text-xl font-semibold ${accent ? 'text-brand' : 'text-text'}`}>
        {value}
      </dd>
    </div>
  )
}
