import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { RegionTable } from '@/components/console/region-table'
import {
  DemoDataBadge,
  KeyValue,
  Meter,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StatCard,
  StateBadge,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { riskToState } from '@/lib/domain/enums'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { getGridSnapshot } from '@/lib/services/grid-service'
import { stabilityBand } from '@/lib/engine/risk'
import { clamp } from '@/lib/engine/rng'

export const metadata: Metadata = { title: 'Grid status' }
export const dynamic = 'force-dynamic'

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

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

  const snapshot = await getGridSnapshot()
  const band = stabilityBand(snapshot.stabilityIndex)
  const canSeeEngineering = user.permissions.has('telemetry.read')

  // The eight published inputs to the stability index, each normalised to 0–100 so the
  // panel shows what the headline number is actually made of.
  const stabilityInputs = [
    {
      key: 'voltage',
      raw: `${formatNumber(locale, snapshot.averageVoltageDeviationPct, { maximumFractionDigits: 2 })}%`,
      score: (1 - clamp(Math.abs(snapshot.averageVoltageDeviationPct) / 6, 0, 1)) * 100,
    },
    {
      key: 'frequency',
      raw: `${formatNumber(locale, snapshot.frequencyHz, { minimumFractionDigits: 3, maximumFractionDigits: 3 })} ${t('common.units.hz')}`,
      score: (1 - clamp(Math.abs(snapshot.frequencyHz - 60) / 0.4, 0, 1)) * 100,
    },
    {
      key: 'load',
      raw: `${formatNumber(locale, snapshot.loadRatio * 100, { maximumFractionDigits: 1 })}%`,
      score: (1 - clamp((snapshot.loadRatio - 0.7) / 0.32, 0, 1)) * 100,
    },
    {
      key: 'reserve',
      raw: `${formatNumber(locale, snapshot.reserveMarginPct, { maximumFractionDigits: 1 })}%`,
      score: clamp(snapshot.reserveMarginPct / 22, 0, 1) * 100,
    },
    {
      key: 'renewable',
      raw: `${formatNumber(locale, snapshot.renewableVariabilityPct, { maximumFractionDigits: 1 })}%`,
      score: (1 - clamp(snapshot.renewableVariabilityPct / 35, 0, 1)) * 100,
    },
    {
      key: 'health',
      raw: formatNumber(locale, snapshot.averageHealth, { maximumFractionDigits: 1 }),
      score: clamp(snapshot.averageHealth, 0, 100),
    },
    {
      key: 'weather',
      raw: `${formatNumber(locale, snapshot.weatherStress * 100, { maximumFractionDigits: 0 })}%`,
      score: (1 - clamp(snapshot.weatherStress, 0, 1)) * 100,
    },
  ]

  // Fleet-wide electrical picture for the engineer view (§22).
  const thermalAssets = snapshot.assets.filter((asset) => asset.profile.assetTypeKey === 'transformer')
  const averageOf = (pick: (asset: (typeof snapshot.assets)[number]) => number) =>
    thermalAssets.length
      ? thermalAssets.reduce((sum, asset) => sum + pick(asset), 0) / thermalAssets.length
      : 0

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

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          label={t('commandCenter.cards.gridStability')}
          value={formatNumber(locale, snapshot.stabilityIndex, { maximumFractionDigits: 1 })}
          hint={t(`stabilityBand.${band}`)}
          state={riskToState(100 - snapshot.stabilityIndex)}
          emphasis
        />
        <StatCard
          label={t('commandCenter.frequency')}
          value={formatNumber(locale, snapshot.frequencyHz, {
            minimumFractionDigits: 3,
            maximumFractionDigits: 3,
          })}
          unit={t('common.units.hz')}
          hint="60.000 ± 0.20"
        />
        <StatCard
          label={t('commandCenter.reserveMargin')}
          value={formatNumber(locale, snapshot.reserveMarginPct, { maximumFractionDigits: 1 })}
          unit="%"
          state={snapshot.reserveMarginPct < 12 ? 'warning' : 'normal'}
        />
        <StatCard
          label={t('commandCenter.averageHealth')}
          value={formatNumber(locale, snapshot.averageHealth, { maximumFractionDigits: 1 })}
          hint={`${snapshot.assets.length} ${t('common.assets').toLowerCase()}`}
        />
      </div>

      <div className="mt-6 grid gap-6 xl:grid-cols-[1.4fr_1fr]">
        <Panel>
          <PanelHeader title={t('grid.regionTable')} />
          <PanelBody>
            <RegionTable
              regions={snapshot.regions.map((region) => ({
                code: region.code,
                name: region.name,
                nameAr: region.nameAr,
                loadMw: region.loadMw,
                capacityMw: region.capacityMw,
                reserveMarginPct: region.reserveMarginPct,
                renewableMw: region.renewableMw,
                renewableSharePct: region.renewableSharePct,
                peakRisk: region.peakRisk,
                averageRisk: region.averageRisk,
                state: region.state,
                assetCount: region.assetCount,
                assetsAtRisk: region.assetsAtRisk,
                averageHealth: region.averageHealth,
                tempC: region.env.tempC,
              }))}
            />
          </PanelBody>
        </Panel>

        <Panel>
          <PanelHeader title={t('grid.stability.title')} subtitle={t('grid.stability.note')} />
          <PanelBody className="space-y-4">
            {stabilityInputs.map((input) => (
              <div key={input.key}>
                <div className="mb-1.5 flex items-baseline justify-between gap-3">
                  <span className="text-xs text-text-muted">{t(`grid.stability.${input.key}`)}</span>
                  <span className="tnum text-xs font-medium text-text">{input.raw}</span>
                </div>
                <Meter value={input.score} state={riskToState(100 - input.score)} />
              </div>
            ))}

            <div className="border-t border-border pt-4">
              <KeyValue
                label={t('grid.stability.incidents')}
                value={formatNumber(locale, snapshot.regions.reduce((sum, r) => sum + r.assetsAtRisk, 0))}
              />
              <KeyValue
                label={t('commandCenter.cards.gridStability')}
                value={
                  <StateBadge
                    state={riskToState(100 - snapshot.stabilityIndex)}
                    label={t(`stabilityBand.${band}`)}
                    size="sm"
                  />
                }
              />
            </div>
          </PanelBody>
        </Panel>
      </div>

      {canSeeEngineering ? (
        <Panel className="mt-6">
          <PanelHeader
            title={t('grid.electrical.title')}
            subtitle={t('grid.engineerView')}
          />
          <PanelBody>
            <dl className="grid gap-x-8 gap-y-1 sm:grid-cols-2 lg:grid-cols-3">
              <KeyValue
                label={t('grid.electrical.voltage')}
                mono
                value={`${formatNumber(locale, snapshot.averageVoltageDeviationPct, { maximumFractionDigits: 2 })}% ${t('grid.stability.voltage')}`}
              />
              <KeyValue
                label={t('grid.electrical.frequency')}
                mono
                value={`${formatNumber(locale, snapshot.frequencyHz, { minimumFractionDigits: 3, maximumFractionDigits: 3 })} ${t('common.units.hz')}`}
              />
              <KeyValue
                label={t('grid.electrical.activePower')}
                mono
                value={`${formatNumber(locale, snapshot.totalLoadMw, { maximumFractionDigits: 0 })} ${t('common.units.mw')}`}
              />
              <KeyValue
                label={t('grid.electrical.reactivePower')}
                mono
                value={`${formatNumber(locale, averageOf((a) => a.sample.reactivePowerMvar) * thermalAssets.length, { maximumFractionDigits: 0 })} ${t('common.units.mvar')}`}
              />
              <KeyValue
                label={t('grid.electrical.powerFactor')}
                mono
                value={formatNumber(locale, averageOf((a) => a.sample.powerFactor), {
                  minimumFractionDigits: 3,
                  maximumFractionDigits: 3,
                })}
              />
              <KeyValue
                label={t('grid.electrical.transformerTemp')}
                mono
                value={`${formatNumber(locale, averageOf((a) => a.sample.tempC), { maximumFractionDigits: 1 })} ${t('common.units.celsius')}`}
              />
              <KeyValue
                label={t('grid.electrical.lineLoading')}
                mono
                value={`${formatNumber(
                  locale,
                  snapshot.assets
                    .filter((a) => a.profile.assetTypeKey === 'transmission_line')
                    .reduce((sum, a, _, list) => sum + a.sample.lineLoadingPct / list.length, 0),
                  { maximumFractionDigits: 1 },
                )}%`}
              />
              <KeyValue
                label={t('grid.electrical.thd')}
                mono
                value={`${formatNumber(locale, averageOf((a) => a.sample.thdPct), { maximumFractionDigits: 2 })}%`}
              />
              <KeyValue
                label={t('grid.electrical.assetHealth')}
                mono
                value={formatNumber(locale, snapshot.averageHealth, { maximumFractionDigits: 1 })}
              />
            </dl>
          </PanelBody>
        </Panel>
      ) : null}
    </>
  )
}
