import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { EvidenceChain } from '@/components/intelligence/evidence-chain'
import { ImpactPanel } from '@/components/intelligence/impact-panel'
import { AssetPicker } from '@/components/intelligence/asset-picker'
import {
  Badge,
  DemoDataBadge,
  ErrorState,
  KeyValue,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { formatDateTime } from '@/lib/i18n/translate'
import { buildEvidence } from '@/lib/services/evidence-service'
import { pickFocusAsset } from '@/lib/services/intelligence-service'

export const metadata: Metadata = { title: 'Evidence Mode' }
export const dynamic = 'force-dynamic'

/**
 * Evidence Mode (§50, §51).
 *
 * The page behind PROVE IT. Everything here is assembled from artefacts the analysis
 * actually produced — where a stage did not run, no node is shown and the gap is named,
 * because a chain with a hole in it must look like one.
 */
export default async function EvidencePage({
  searchParams,
}: {
  searchParams: Promise<{ asset?: string; twin?: string }>
}) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('evidence.read')) return <PermissionGate />

  const { asset, twin } = await searchParams
  const assetCode = asset ?? (await pickFocusAsset())
  if (!assetCode) {
    return (
      <>
        <PageHeader title={t('evidence.title')} subtitle={t('evidence.subtitle')} />
        <ErrorState title={t('uiState.empty')} body={t('evidence.subtitle')} />
      </>
    )
  }

  const view = await buildEvidence({ assetCode, twinCode: twin ?? 'TWIN-SITE-SS-RYD-01' })

  if (!view) {
    return (
      <>
        <PageHeader title={t('evidence.title')} subtitle={t('evidence.subtitle')} />
        <ErrorState title={t('uiState.error')} body={assetCode} />
      </>
    )
  }

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

      <div className="grid gap-4 xl:grid-cols-[minmax(0,1.35fr)_minmax(0,1fr)]">
        <div className="min-w-0 space-y-4">
          <EvidenceChain bundle={view.bundle} />
        </div>

        <div className="min-w-0 space-y-4">
          <ImpactPanel impact={view.impact} />

          {/* ── Reproducibility (§53) ────────────────────────────────────────── */}
          <Panel>
            <PanelHeader
              title={t('evidence.reproducible')}
              action={<Badge tone="brand">{t('common.simulated')}</Badge>}
            />
            <PanelBody className="space-y-2">
              <KeyValue
                label={t('evidence.model')}
                value={view.reproducibility.modelVersion || '—'}
              />
              <KeyValue
                label={t('twin.title')}
                value={view.reproducibility.twinVersion || '—'}
              />
              <KeyValue
                label={t('evidence.snapshot')}
                value={<span className="font-mono text-[11px]">{view.reproducibility.dataSnapshotId}</span>}
              />
              <KeyValue
                label={t('common.asOf')}
                value={formatDateTime(locale, view.reproducibility.ts)}
              />
              <p className="pt-1 text-[11px] leading-relaxed text-text-faint">
                {t('evidence.reproducibleNote')}
              </p>
            </PanelBody>
          </Panel>
        </div>
      </div>
    </>
  )
}
