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

import { PermissionGate } from '@/components/console/permission-gate'
import { AgentActivity } from '@/components/intelligence/agent-activity'
import { AgentFlow } from '@/components/intelligence/agent-flow'
import { DecisionLens } from '@/components/intelligence/decision-lens'
import { DnaVisual } from '@/components/intelligence/dna-visual'
import { StrategyMatrix } from '@/components/intelligence/strategy-matrix'
import { AssetPicker } from '@/components/intelligence/asset-picker'
import { CascadeTimeline } from '@/components/intelligence/cascade-timeline'
import { ConfidencePanel } from '@/components/intelligence/confidence-panel'
import { FutureBranches } from '@/components/intelligence/future-branches'
import { IncidentClock } from '@/components/intelligence/incident-clock'
import { PreventionWindowPanel } from '@/components/intelligence/prevention-window'
import { RootCausePanel } from '@/components/intelligence/root-cause-panel'
import { StrategyTable } from '@/components/intelligence/strategy-table'
import {
  Badge,
  DemoDataBadge,
  ErrorState,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StatCard,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { formatDateTime, formatNumber } from '@/lib/i18n/translate'
import { getWarRoom } from '@/lib/services/warroom-service'

export const metadata: Metadata = { title: 'AI War Room' }
export const dynamic = 'force-dynamic'

/**
 * The AI War Room (§21–§23).
 *
 * Opens on whichever asset most needs it unless one is named. Everything on the page is
 * about that single situation: the clock, the chain, the futures, the strategies and the
 * approval the operator is being asked for — nothing else from the console competes for
 * attention here.
 */
export default async function WarRoomPage({
  searchParams,
}: {
  searchParams: Promise<{ asset?: string }>
}) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('warroom.access')) return <PermissionGate />

  const { asset } = await searchParams
  const state = await getWarRoom({ assetCode: asset?.trim() || undefined })

  if (!state) {
    return (
      <>
        <PageHeader title={t('warRoom.title')} subtitle={t('warRoom.subtitle')} />
        <ErrorState title={t('errors.NOT_FOUND')} body={asset ?? ''} />
      </>
    )
  }

  const { intel } = state
  const { orchestration } = intel

  return (
    <>
      <PageHeader
        title={t('warRoom.title')}
        subtitle={t('warRoom.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
        action={<AssetPicker current={intel.assetCode} />}
      />

      {/* Incident header (§51): the identifiers and the four numbers a responder reads
          first, on one line, before any panel. */}
      <div className="mb-4 flex flex-wrap items-center gap-x-5 gap-y-2 rounded-[--radius-panel] border border-border bg-surface-2/50 px-4 py-2.5 text-[11px]">
        <span className="font-mono font-semibold text-brand">
          NR-{new Date(intel.ts).getFullYear()}-{String(Math.abs(intel.assetCode.split('').reduce((sum, char) => sum + char.charCodeAt(0), 0)) % 10000).padStart(4, '0')}
        </span>
        <span className="text-text">{intel.focus.profile.regionCode}</span>
        <span className="font-mono text-text">{intel.assetCode}</span>
        <span className="tnum text-text-muted">
          {t('aiOps.unifiedRisk')}{' '}
          <span className="font-semibold text-critical">
            {formatNumber(locale, orchestration.unifiedRisk, { maximumFractionDigits: 0 })}%
          </span>
        </span>
        <span className="tnum text-text-muted">
          {t('preventionWindow.eventIn')}{' '}
          {orchestration.preventionWindow.etaMinutes === null
            ? '—'
            : `~${formatNumber(locale, orchestration.preventionWindow.etaMinutes)} ${t('common.minutes')}`}
        </span>
        <span className="tnum text-text-muted">
          {t('preventionWindow.safeWindow')}{' '}
          ~{formatNumber(locale, orchestration.preventionWindow.safeWindowMin)} {t('common.minutes')}
        </span>
        <span className="tnum ms-auto text-text-muted">
          {t('confidence.data')}{' '}
          {formatNumber(locale, orchestration.confidence.data, { maximumFractionDigits: 0 })}%
        </span>
      </div>

      <Panel glow>
        <PanelHeader
          title={state.active ? t('warRoom.activeTitle') : t('warRoom.standbyTitle')}
          subtitle={state.active ? t('warRoom.activeBody') : t('warRoom.standbyBody')}
          action={
            <Badge tone={state.active ? 'accent' : 'muted'}>
              {t('warRoom.threshold')} {formatNumber(locale, state.threshold, { maximumFractionDigits: 0 })}%
            </Badge>
          }
        />
        <PanelBody className="pt-0">
          <div className="grid items-center gap-4 lg:grid-cols-[16rem_1fr]">
            <IncidentClock seconds={state.secondsToEvent} className="rounded-lg border border-border bg-surface-2/50 p-4" />
            <div>
              <div className="grid gap-3 sm:grid-cols-3">
                <StatCard
                  label={t('aiOps.unifiedRisk')}
                  value={formatNumber(locale, orchestration.unifiedRisk, { maximumFractionDigits: 0 })}
                  unit="%"
                  emphasis
                  state={
                    orchestration.unifiedRisk >= 70
                      ? 'critical'
                      : orchestration.unifiedRisk >= 45
                        ? 'warning'
                        : 'normal'
                  }
                  hint={t(`aiOps.band.${orchestration.band}`)}
                />
                <StatCard
                  label={t('cascade.affectedCustomers')}
                  value={formatNumber(locale, intel.cascade.affectedCustomers)}
                  hint={`${formatNumber(locale, intel.cascade.affectedAssets)} ${t('cascade.affectedAssets')}`}
                />
                <StatCard
                  label={t('aiOps.focusAsset')}
                  value={intel.assetCode}
                  href={`/assets/${encodeURIComponent(intel.assetCode)}`}
                  hint={`${formatNumber(locale, intel.focus.sample.loadPct, { maximumFractionDigits: 0 })}% · ${formatNumber(locale, intel.focus.sample.tempC, { maximumFractionDigits: 0 })} °C`}
                />
              </div>
              <p className="mt-3 text-xs leading-relaxed text-text-muted">
                {locale === 'ar' ? orchestration.rationaleAr : orchestration.rationale}
              </p>
            </div>
          </div>
        </PanelBody>
      </Panel>

      <div className="mt-6 grid gap-4 lg:grid-cols-[1fr_22rem]">
        <div className="min-w-0 space-y-4">
          <CascadeTimeline result={intel.cascade} showStats={false} />
          <FutureBranches branches={state.branches} horizonMin={intel.prediction.horizonMin} />
          <StrategyTable strategies={intel.optimisation.strategies} />
          <StrategyMatrix strategies={intel.optimisation.strategies} />
        </div>

        <div className="min-w-0 space-y-4">
          <PreventionWindowPanel
            window={orchestration.preventionWindow}
            uncertainty={orchestration.uncertainty}
          />
          <ConfidencePanel
            confidence={orchestration.confidence}
            warning={locale === 'ar' ? orchestration.dataWarningAr : orchestration.dataWarning}
          />
          <AgentActivity agents={intel.agents} startedAt={intel.ts} />
          <DecisionLens factors={intel.focus.risk.topFactors} />
          <AgentFlow flow={orchestration.flow} />

          <Panel>
            <PanelHeader title={t('warRoom.patterns')} />
            <PanelBody className="pt-0">
              {state.patterns.length === 0 ? (
                <p className="py-2 text-xs text-text-muted">{t('warRoom.noPatterns')}</p>
              ) : (
                <ul className="divide-y divide-border/60">
                  {state.patterns.map((pattern) => (
                    <li key={pattern.code} className="py-2">
                      <div className="flex items-baseline justify-between gap-2">
                        <p className="font-mono text-[11px] text-text">{pattern.code}</p>
                        <p className="tnum text-[11px] text-brand">
                          {formatNumber(locale, pattern.similarity, { maximumFractionDigits: 0 })}%
                        </p>
                      </div>
                      <p className="mt-0.5 text-[11px] text-text-muted">
                        {locale === 'ar' ? pattern.labelAr : pattern.label}
                      </p>
                    </li>
                  ))}
                </ul>
              )}
            </PanelBody>
          </Panel>

          <Panel>
            <PanelHeader
              title={t('warRoom.decisions')}
              action={
                user.permissions.has('decisions.read') ? (
                  <Link href="/decisions" className="text-[11px] font-medium text-brand hover:underline">
                    {t('notifications.viewAll')}
                  </Link>
                ) : null
              }
            />
            <PanelBody className="pt-0">
              {state.decisions.length === 0 ? (
                <p className="py-2 text-xs text-text-muted">{t('warRoom.noDecisions')}</p>
              ) : (
                <ul className="divide-y divide-border/60">
                  {state.decisions.map((decision) => (
                    <li key={decision.code} className="py-2">
                      <div className="flex items-baseline justify-between gap-2">
                        <p className="text-[11px] font-medium text-text">
                          {locale === 'ar' ? decision.titleAr : decision.title}
                        </p>
                        <Badge tone="muted">{t(`decisions.status.${decision.status}`)}</Badge>
                      </div>
                      <p className="tnum mt-0.5 text-[10px] text-text-faint">
                        {formatDateTime(locale, decision.createdAt)} ·{' '}
                        {formatNumber(locale, decision.riskBefore, { maximumFractionDigits: 0 })}% →{' '}
                        {formatNumber(locale, decision.riskAfter, { maximumFractionDigits: 0 })}%
                      </p>
                    </li>
                  ))}
                </ul>
              )}
            </PanelBody>
          </Panel>
        </div>
      </div>

      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <RootCausePanel result={intel.rootCause} />
        {intel.dnaMatches[0] ? (
          <DnaVisual
            patternCode={intel.dnaMatches[0].pattern.code}
            patternName={intel.dnaMatches[0].pattern.name}
            patternNameAr={intel.dnaMatches[0].pattern.nameAr}
            similarity={intel.dnaMatches[0].similarity}
            contributions={intel.dnaMatches[0].contributions}
          />
        ) : null}
      </div>
    </>
  )
}
