import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { RedBlueLab } from '@/components/intelligence/red-blue-lab'
import { ResilienceLab } from '@/components/intelligence/resilience-lab'
import { WhatBreaksFirst } from '@/components/intelligence/wow-actions'
import { StressTestRunner } from '@/components/intelligence/stress-test-runner'
import {
  Badge,
  DemoDataBadge,
  Meter,
  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 { getResilience, listResilienceTests } from '@/lib/services/resilience-service'
import { listStressScenarios } from '@/lib/services/red-blue-service'
import { pickFocusAsset } from '@/lib/services/intelligence-service'
import { cn } from '@/lib/cn'

export const metadata: Metadata = { title: 'Resilience Lab' }
export const dynamic = 'force-dynamic'

/**
 * Resilience (§39–§42).
 *
 * The score and the envelope are computed on the server so the page opens with real
 * numbers; the disturbance test and the adversarial search are interactive because they
 * are experiments, and an experiment that ran before you asked for it is not an
 * experiment.
 */
export default async function ResiliencePage() {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('grid.read')) return <PermissionGate />

  const [resilience, tests, focusAsset] = await Promise.all([
    getResilience({ includeEnvelope: true }),
    listResilienceTests(6),
    pickFocusAsset(),
  ])
  const stressScenarios = listStressScenarios()

  const envelope = resilience.envelope
  // Where the current loading sits inside the safe band, as a percentage of the band.
  const utilisation = Math.min(
    130,
    (envelope.currentLoadPct / Math.max(envelope.heatAdjustedMaxPct, 1)) * 100,
  )

  return (
    <>
      <PageHeader
        title={t('resilience.title')}
        subtitle={t('resilience.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('resilience.score')}
          value={formatNumber(locale, resilience.score, { maximumFractionDigits: 0 })}
          emphasis
          hint={t(`resilience.band.${resilience.band}`)}
          state={
            resilience.score >= 80
              ? 'normal'
              : resilience.score >= 62
                ? 'watch'
                : resilience.score >= 42
                  ? 'warning'
                  : 'critical'
          }
        />
        <StatCard
          label={t('resilience.currentLoad')}
          value={formatNumber(locale, envelope.currentLoadPct, { maximumFractionDigits: 1 })}
          unit="%"
        />
        <StatCard
          label={t('resilience.heatAdjusted')}
          value={formatNumber(locale, envelope.heatAdjustedMaxPct, { maximumFractionDigits: 1 })}
          unit="%"
          hint={`${t('resilience.maxRecommended')} ${formatNumber(locale, envelope.maxRecommendedPct, { maximumFractionDigits: 1 })}%`}
        />
        <StatCard
          label={t('resilience.headroom')}
          value={formatNumber(locale, envelope.headroomPct, { maximumFractionDigits: 1 })}
          unit="%"
          state={envelope.headroomPct > 8 ? 'normal' : envelope.headroomPct > 3 ? 'warning' : 'critical'}
        />
      </div>

      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <Panel>
          <PanelHeader
            title={t('resilience.score')}
            subtitle={locale === 'ar' ? resilience.summaryAr : resilience.summary}
            action={<Badge tone="muted">{t(`resilience.band.${resilience.band}`)}</Badge>}
          />
          <PanelBody className="space-y-2.5 pt-0">
            {resilience.components.map((component) => (
              <div key={component.key}>
                <div className="flex items-baseline justify-between gap-3 text-[11px]">
                  <span className="text-text-muted">{t(`resilience.factor.${component.key}`)}</span>
                  <span className="tnum text-text-faint">
                    {formatNumber(locale, component.value, { maximumFractionDigits: 1 })}
                    {component.unit}
                    <span className="ms-2 font-medium text-text">
                      {formatNumber(locale, component.normalised, { maximumFractionDigits: 0 })}
                    </span>
                  </span>
                </div>
                <Meter
                  className="mt-1"
                  value={component.normalised}
                  state={
                    component.normalised >= 70 ? 'normal' : component.normalised >= 45 ? 'watch' : 'critical'
                  }
                />
              </div>
            ))}
            {resilience.weakest ? (
              <p className="rounded-lg border border-watch/30 bg-watch/8 px-3 py-2 text-[11px] text-watch">
                {t('resilience.weakest')}: {t(`resilience.factor.${resilience.weakest.key}`)}
              </p>
            ) : null}
          </PanelBody>
        </Panel>

        <Panel>
          <PanelHeader title={t('resilience.envelope')} subtitle={t('resilience.envelopeHint')} />
          <PanelBody className="pt-0">
            {/* The band, drawn. Safe zone to the recommended ceiling, danger beyond it,
                and a marker where the grid is actually running. */}
            <div className="relative h-8 w-full overflow-hidden rounded-lg border border-border bg-surface-3">
              <div
                className="absolute inset-y-0 bg-normal/25"
                style={{ insetInlineStart: 0, width: `${Math.min(100, envelope.heatAdjustedMaxPct)}%` }}
              />
              <div
                className="absolute inset-y-0 bg-critical/25"
                style={{
                  insetInlineStart: `${Math.min(100, envelope.heatAdjustedMaxPct)}%`,
                  width: `${Math.max(0, 100 - envelope.heatAdjustedMaxPct)}%`,
                }}
              />
              <div
                className="absolute inset-y-0 w-0.5 bg-brand"
                style={{ insetInlineStart: `${Math.min(100, envelope.currentLoadPct)}%` }}
              />
            </div>
            <div className="mt-2 flex items-center justify-between text-[10px] text-text-faint">
              <span className="text-normal">{t('resilience.safeZone')}</span>
              <span className="text-critical">{t('resilience.dangerZone')}</span>
            </div>

            <dl className="mt-4 grid gap-x-6 gap-y-1 text-[11px] sm:grid-cols-2">
              <div className="flex items-baseline justify-between gap-2">
                <dt className="text-text-muted">{t('resilience.currentLoad')}</dt>
                <dd className="tnum font-medium text-text">
                  {formatNumber(locale, envelope.currentLoadPct, { maximumFractionDigits: 1 })}%
                </dd>
              </div>
              <div className="flex items-baseline justify-between gap-2">
                <dt className="text-text-muted">{t('resilience.maxRecommended')}</dt>
                <dd className="tnum font-medium text-text">
                  {formatNumber(locale, envelope.maxRecommendedPct, { maximumFractionDigits: 1 })}%
                </dd>
              </div>
              <div className="flex items-baseline justify-between gap-2">
                <dt className="text-text-muted">{t('resilience.heatAdjusted')}</dt>
                <dd className="tnum font-medium text-text">
                  {formatNumber(locale, envelope.heatAdjustedMaxPct, { maximumFractionDigits: 1 })}%
                </dd>
              </div>
              <div className="flex items-baseline justify-between gap-2">
                <dt className="text-text-muted">{t('resilience.factor.availableCapacity')}</dt>
                <dd className="tnum font-medium text-text">
                  {formatNumber(locale, envelope.reserveMarginPct, { maximumFractionDigits: 1 })}%
                </dd>
              </div>
            </dl>

            {!envelope.isInsideEnvelope ? (
              <p className="mt-3 rounded-lg border border-critical/30 bg-critical/8 px-3 py-2 text-[11px] text-critical">
                {t('resilience.outsideEnvelope')}
              </p>
            ) : null}

            <p className={cn('mt-3 text-[10px] text-text-faint')}>
              {formatNumber(locale, utilisation, { maximumFractionDigits: 0 })}% ·{' '}
              {t('resilience.envelopeHint')}
            </p>
          </PanelBody>
        </Panel>
      </div>

      <div className="mt-6">
        <ResilienceLab defaultAsset={focusAsset ?? 'T-108'} />
      </div>

      {/* 4.0: the stress and the response searched as a pair (§24–§26). A stress test on
          its own says the grid bends; running the response search against the resources
          the scenario left behind says whether it can be straightened. */}
      {user.permissions.has('resilience.run') ? (
        <div className="mt-6 grid gap-4 xl:grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)]">
          <div className="min-w-0">
            <RedBlueLab
              scenarios={stressScenarios}
              regions={REGIONS.map((region) => ({
                code: region.code,
                name: region.name,
                nameAr: region.nameAr,
              }))}
              canRun
            />
          </div>
          <div className="min-w-0">
            <WhatBreaksFirst assetCode={focusAsset ?? 'T-108'} />
          </div>
        </div>
      ) : null}

      {user.permissions.has('stress.run') ? (
        <div className="mt-6">
          <StressTestRunner
            regions={REGIONS.map((region) => ({
              code: region.code,
              name: region.name,
              nameAr: region.nameAr,
            }))}
          />
        </div>
      ) : null}

      <Panel className="mt-6">
        <PanelHeader title={t('resilience.history')} />
        <PanelBody className="pt-0">
          {tests.length === 0 ? (
            <p className="py-2 text-xs text-text-muted">{t('resilience.noHistory')}</p>
          ) : (
            <ul className="divide-y divide-border/60">
              {tests.map((test) => (
                <li key={test.code} className="flex flex-wrap items-baseline justify-between gap-3 py-2">
                  <div className="min-w-0">
                    <p className="text-[11px] font-medium text-text">
                      {t(`resilience.disturbance.${test.disturbance}`)}
                    </p>
                    <p className="mt-0.5 text-[11px] leading-relaxed text-text-muted">
                      {locale === 'ar' ? test.verdictAr : test.verdict}
                    </p>
                  </div>
                  <span className="tnum shrink-0 text-[11px] text-text-faint">
                    {formatNumber(locale, test.scoreBefore, { maximumFractionDigits: 0 })} →{' '}
                    {formatNumber(locale, test.scoreDuring, { maximumFractionDigits: 0 })} →{' '}
                    {formatNumber(locale, test.scoreAfter, { maximumFractionDigits: 0 })}
                  </span>
                </li>
              ))}
            </ul>
          )}
        </PanelBody>
      </Panel>
    </>
  )
}
