import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { AgentBoard } from '@/components/intelligence/agent-board'
import { AgentFlow } from '@/components/intelligence/agent-flow'
import { AssetPicker } from '@/components/intelligence/asset-picker'
import { ConfidencePanel } from '@/components/intelligence/confidence-panel'
import { PreventionWindowPanel } from '@/components/intelligence/prevention-window'
import { OperatingEnvelopePanel, PhysicsValidationPanel } from '@/components/intelligence/physics-panel'
import { RootCausePanel } from '@/components/intelligence/root-cause-panel'
import { SimilarDecisions } from '@/components/intelligence/similar-decisions'
import { TrustDialog } from '@/components/intelligence/trust-dialog'
import { UncertaintyPanel } from '@/components/intelligence/uncertainty-panel'
import { WeakSignalsPanel } from '@/components/intelligence/weak-signals-panel'
import {
  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 { formatNumber } from '@/lib/i18n/translate'
import { analyseAsset, pickFocusAsset } from '@/lib/services/intelligence-service'
import { contextFromIntelligence, findSimilarDecisions } from '@/lib/services/memory-service'

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

/**
 * The AI Operations Room (§4).
 *
 * One asset, eight agents and the orchestrator's reconciliation of them. The whole pass
 * runs server-side on request, so what a judge sees was computed for the instant they
 * pressed reload — not read out of a table.
 */
export default async function AiOperationsPage({
  searchParams,
}: {
  searchParams: Promise<{ asset?: string }>
}) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('agents.read')) return <PermissionGate />

  const { asset } = await searchParams
  const assetCode = asset?.trim() || (await pickFocusAsset())
  const intel = assetCode ? await analyseAsset(assetCode) : null

  if (!intel) {
    return (
      <>
        <PageHeader title={t('aiOps.title')} subtitle={t('aiOps.subtitle')} />
        <ErrorState title={t('errors.NOT_FOUND')} body={assetCode ?? ''} />
      </>
    )
  }

  const { orchestration } = intel

  // "Have we seen this before?" runs against the same situation the agents just analysed,
  // so the matches are for the state on screen rather than for the asset in general (§29).
  const similar = user.permissions.has('memory.read')
    ? await findSimilarDecisions(contextFromIntelligence(intel), { limit: 3 })
    : []

  return (
    <>
      <PageHeader
        title={t('aiOps.title')}
        subtitle={t('aiOps.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
        action={
          <div className="flex min-w-0 max-w-full flex-wrap items-end gap-2">
            <AssetPicker current={intel.assetCode} />
            {/* PROVE IT, on the page where the claim is actually made (§51). */}
            <TrustDialog assetCode={intel.assetCode} label={t('common.proveIt')} />
          </div>
        }
      />

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <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('aiOps.focusAsset')}
          value={intel.assetCode}
          hint={`${formatNumber(locale, intel.focus.sample.loadPct, { maximumFractionDigits: 0 })}% · ${formatNumber(locale, intel.focus.sample.tempC, { maximumFractionDigits: 0 })} °C`}
          href={`/assets/${encodeURIComponent(intel.assetCode)}`}
        />
        <StatCard
          label={t('confidence.overall')}
          value={formatNumber(locale, orchestration.confidence.overall, { maximumFractionDigits: 0 })}
          unit="%"
          hint={t(`confidence.band.${orchestration.confidence.band}`)}
        />
        <StatCard
          label={t('preventionWindow.safeWindow')}
          value={
            orchestration.preventionWindow.safeWindowMin > 0
              ? formatNumber(locale, orchestration.preventionWindow.safeWindowMin)
              : '—'
          }
          unit={t('common.minutes')}
          state={orchestration.preventionWindow.expired ? 'critical' : 'normal'}
        />
      </div>

      <Panel className="mt-6" glow>
        <PanelHeader title={t('aiOps.rationale')} subtitle={intel.assetCode} />
        <PanelBody className="pt-0">
          <p className="text-sm leading-relaxed text-text">
            {locale === 'ar' ? orchestration.rationaleAr : orchestration.rationale}
          </p>
        </PanelBody>
      </Panel>

      <div className="mt-6 grid gap-4 lg:grid-cols-[1fr_22rem]">
        <AgentBoard agents={intel.agents} />
        <div className="min-w-0 space-y-4">
          <AgentFlow flow={orchestration.flow} />
          <ConfidencePanel
            confidence={orchestration.confidence}
            warning={locale === 'ar' ? orchestration.dataWarningAr : orchestration.dataWarning}
          />
        </div>
      </div>

      {/* ── 4.0: the belief around the prediction, and the limits around the plan ──── */}
      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <div className="min-w-0">
          <UncertaintyPanel view={intel.uncertainty} />
        </div>
        <div className="min-w-0 space-y-4">
          <OperatingEnvelopePanel envelope={intel.envelope} />
          <PhysicsValidationPanel
            verdict={intel.physics.verdict}
            checks={intel.physics.checks}
            summary={intel.physics.summary}
            summaryAr={intel.physics.summaryAr}
            confidence={intel.physics.confidence}
          />
        </div>
      </div>

      {similar.length ? (
        <div className="mt-6">
          <SimilarDecisions
            matches={similar.map((match) => ({
              code: match.record.code,
              title: match.record.title,
              titleAr: match.record.titleAr,
              similarity: match.similarity,
              strategyLabel: match.record.strategyLabel,
              strategyLabelAr: match.record.strategyLabelAr,
              riskBefore: match.record.riskBefore,
              riskAfter: match.record.riskAfter,
              outcomeStatus: match.record.outcomeStatus,
              evidenceKind: match.record.evidenceKind,
              evidenceLabel: match.evidenceLabel,
              evidenceLabelAr: match.evidenceLabelAr,
              headline: match.headline,
              headlineAr: match.headlineAr,
              contributions: match.contributions,
            }))}
          />
        </div>
      ) : null}

      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <RootCausePanel result={intel.rootCause} />
        <div className="min-w-0 space-y-4">
          <PreventionWindowPanel
            window={orchestration.preventionWindow}
            uncertainty={orchestration.uncertainty}
          />
          <WeakSignalsPanel result={intel.weakSignals} />
        </div>
      </div>
    </>
  )
}
