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

import { PermissionGate } from '@/components/console/permission-gate'
import { PrintButton } from '@/components/console/print-button'
import {
  Badge,
  DemoDataBadge,
  KeyValue,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
} 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 { analyseAsset, futureBranches, pickFocusAsset } from '@/lib/services/intelligence-service'
import { getResilience } from '@/lib/services/resilience-service'
import { getTwinState, listTwinSimulations } from '@/lib/services/twin-service'
import { listDecisions, storedConfidence } from '@/lib/services/decision-service'
import { cn } from '@/lib/cn'

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

const KINDS = ['executive', 'risk', 'twin', 'simulation', 'resilience'] as const
type Kind = (typeof KINDS)[number]

/**
 * Reports (§86–§89).
 *
 * A report is the same computation as the screen, laid out to leave the building. There
 * is no separate reporting pipeline and no cached figures: opening a report recomputes
 * it, which is the only way to guarantee that a printed page and the console agree.
 *
 * Printing is the browser's, deliberately. A PDF library would add a large dependency to
 * reproduce, imperfectly, what every browser already does well — and the print stylesheet
 * is already part of the design system.
 */
export default async function ReportsPage({
  searchParams,
}: {
  searchParams: Promise<{ kind?: string; asset?: string }>
}) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('grid.read')) return <PermissionGate />

  const { kind: requested, asset } = await searchParams
  const kind: Kind = (KINDS as readonly string[]).includes(requested ?? '') ? (requested as Kind) : 'executive'

  const assetCode = asset?.trim() || (await pickFocusAsset())
  const [intel, resilience, twinState, simulations, decisions] = await Promise.all([
    assetCode ? analyseAsset(assetCode) : null,
    kind === 'resilience' || kind === 'executive'
      ? getResilience({ includeEnvelope: false })
      : null,
    kind === 'twin' ? getTwinState('TWIN-NATIONAL') : null,
    kind === 'simulation' ? listTwinSimulations('TWIN-NATIONAL', 10) : null,
    kind === 'executive' ? listDecisions({ limit: 5 }) : null,
  ])
  const branches = intel && kind !== 'twin' ? await futureBranches(intel) : null

  const generatedAt = Date.now()
  const ar = locale === 'ar'

  return (
    <>
      <div className="no-print">
        <PageHeader
          title={t('reports.title')}
          subtitle={t('reports.subtitle')}
          badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
          action={<PrintButton label={t('reports.print')} />}
        />

        <div className="mb-6 flex flex-wrap gap-2">
          {KINDS.map((entry) => (
            <Link
              key={entry}
              href={`/reports?kind=${entry}${assetCode ? `&asset=${encodeURIComponent(assetCode)}` : ''}`}
              className={cn(
                'rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors',
                entry === kind
                  ? 'border-brand/50 bg-brand/12 text-brand'
                  : 'border-border bg-surface-2 text-text-muted hover:border-border-strong hover:text-text',
              )}
            >
              {t(`reports.${entry}`)}
            </Link>
          ))}
        </div>
      </div>

      <article className="space-y-4">
        <Panel>
          <PanelHeader
            title={t(`reports.${kind}`)}
            subtitle={`${t('reports.generatedAt')}: ${formatDateTime(locale, generatedAt)}`}
            action={<Badge tone="accent">{t('common.simulated')}</Badge>}
          />
          <PanelBody className="pt-0">
            <div className="grid gap-x-8 gap-y-1 sm:grid-cols-2">
              <KeyValue label={t('reports.shareable')} value={`RPT-${generatedAt.toString(36).toUpperCase()}`} mono />
              {assetCode ? <KeyValue label={t('aiOps.focusAsset')} value={assetCode} mono /> : null}
              <KeyValue label={t('source.label')} value={t('source.simulated')} />
              <KeyValue label={t('common.simulated')} value={t('futures.estimate')} />
            </div>
          </PanelBody>
        </Panel>

        {/* ── Executive brief (§39) ──────────────────────────────────────── */}
        {kind === 'executive' && intel ? (
          <Panel>
            <PanelHeader title={t('reports.executive')} />
            <PanelBody className="space-y-3 pt-0">
              <p className="text-sm leading-relaxed text-text">
                {ar ? intel.orchestration.rationaleAr : intel.orchestration.rationale}
              </p>
              <div className="grid gap-x-8 gap-y-1 sm:grid-cols-2">
                <KeyValue
                  label={t('commandCenter.cards.gridStability')}
                  value={formatNumber(locale, intel.snapshot.stabilityIndex, { maximumFractionDigits: 1 })}
                  mono
                />
                <KeyValue
                  label={t('aiOps.unifiedRisk')}
                  value={`${formatNumber(locale, intel.orchestration.unifiedRisk, { maximumFractionDigits: 0 })}%`}
                  mono
                />
                <KeyValue
                  label={t('resilience.score')}
                  value={resilience ? formatNumber(locale, resilience.score, { maximumFractionDigits: 0 }) : '—'}
                  mono
                />
                <KeyValue
                  label={t('preventionWindow.eventIn')}
                  value={
                    intel.prediction.etaMinutes === null
                      ? t('common.notAvailable')
                      : `${formatNumber(locale, intel.prediction.etaMinutes)} ${t('common.minutes')}`
                  }
                  mono
                />
              </div>

              {intel.orchestration.recommended ? (
                <div className="rounded-lg border border-brand/35 bg-brand/6 p-3">
                  <p className="text-[10px] uppercase tracking-wide text-text-faint">
                    {t('selfHealing.recommended')}
                  </p>
                  <p className="mt-1 text-sm font-medium text-text">
                    {ar
                      ? intel.orchestration.recommended.labelAr
                      : intel.orchestration.recommended.label}
                  </p>
                  <p className="tnum mt-1 text-xs text-text-muted">
                    {formatNumber(locale, intel.orchestration.recommended.evaluation.riskBefore, { maximumFractionDigits: 0 })}
                    % → {formatNumber(locale, intel.orchestration.recommended.evaluation.riskAfter, { maximumFractionDigits: 0 })}%
                  </p>
                </div>
              ) : null}

              {decisions && decisions.length > 0 ? (
                <div>
                  <p className="text-[10px] uppercase tracking-wide text-text-faint">
                    {t('trust.decisions')}
                  </p>
                  <ul className="mt-1.5 space-y-1">
                    {decisions.map((decision) => (
                      <li key={decision.code} className="flex items-baseline justify-between gap-3 text-[11px]">
                        <span className="text-text-muted">{ar ? decision.titleAr : decision.title}</span>
                        <span className="tnum text-text-faint">
                          {t(`decisions.status.${decision.status}`)} ·{' '}
                          {formatNumber(locale, storedConfidence(decision).overall, { maximumFractionDigits: 0 })}%
                        </span>
                      </li>
                    ))}
                  </ul>
                </div>
              ) : null}
            </PanelBody>
          </Panel>
        ) : null}

        {/* ── Risk report ────────────────────────────────────────────────── */}
        {kind === 'risk' && intel ? (
          <Panel>
            <PanelHeader title={t('reports.risk')} subtitle={intel.assetCode} />
            <PanelBody className="space-y-3 pt-0">
              <p className="text-sm leading-relaxed text-text">
                {ar ? intel.rootCause.summaryAr : intel.rootCause.summary}
              </p>
              <table className="w-full text-xs">
                <thead>
                  <tr className="border-b border-border text-[10px] uppercase tracking-wide text-text-faint">
                    <th className="py-2 text-start font-medium">{t('rootCause.evidence')}</th>
                    <th className="py-2 text-end font-medium">{t('common.riskScore')}</th>
                  </tr>
                </thead>
                <tbody>
                  {intel.focus.risk.topFactors.map((factor) => (
                    <tr key={factor.key} className="border-b border-border/40 last:border-0">
                      <td className="py-1.5 text-text-muted">{t(`riskFactor.${factor.key}`)}</td>
                      <td className="tnum py-1.5 text-end text-text">
                        +{formatNumber(locale, factor.contribution, { maximumFractionDigits: 1 })}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </PanelBody>
          </Panel>
        ) : null}

        {/* ── Digital twin report ────────────────────────────────────────── */}
        {kind === 'twin' && twinState ? (
          <Panel>
            <PanelHeader title={t('reports.twin')} subtitle={twinState.twin.code} />
            <PanelBody className="pt-0">
              <div className="grid gap-x-8 gap-y-1 sm:grid-cols-2">
                <KeyValue label={t('twin.members')} value={formatNumber(locale, twinState.assets.length)} mono />
                <KeyValue
                  label={t('twin.fidelity')}
                  value={`${formatNumber(locale, twinState.fidelity.score, { maximumFractionDigits: 0 })}%`}
                  mono
                />
                <KeyValue
                  label={t('twin.sensorsOnline')}
                  value={`${formatNumber(locale, twinState.fidelity.sensorsOnline)} / ${formatNumber(locale, twinState.fidelity.sensorsExpected)}`}
                  mono
                />
                <KeyValue
                  label={t('commandCenter.cards.gridStability')}
                  value={formatNumber(locale, twinState.snapshot.stabilityIndex, { maximumFractionDigits: 1 })}
                  mono
                />
              </div>
            </PanelBody>
          </Panel>
        ) : null}

        {/* ── Simulation report, before and after (§88) ──────────────────── */}
        {kind === 'simulation' && simulations ? (
          <Panel>
            <PanelHeader title={t('reports.beforeAfter')} />
            <PanelBody className="pt-0">
              {simulations.length === 0 ? (
                <p className="py-2 text-xs text-text-muted">{t('uiState.empty')}</p>
              ) : (
                <table className="w-full text-xs">
                  <thead>
                    <tr className="border-b border-border text-[10px] uppercase tracking-wide text-text-faint">
                      <th className="py-2 text-start font-medium">{t('reports.simulation')}</th>
                      <th className="py-2 text-end font-medium">{t('counterfactual.before')}</th>
                      <th className="py-2 text-end font-medium">{t('counterfactual.after')}</th>
                      <th className="py-2 text-end font-medium">{t('reports.change')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {simulations.map((simulation) => (
                      <tr key={simulation.code} className="border-b border-border/40 last:border-0">
                        <td className="py-1.5 font-mono text-[10px] text-text-muted">{simulation.code}</td>
                        <td className="tnum py-1.5 text-end text-critical">
                          {formatNumber(locale, simulation.riskBefore, { maximumFractionDigits: 0 })}%
                        </td>
                        <td className="tnum py-1.5 text-end text-normal">
                          {formatNumber(locale, simulation.riskAfter, { maximumFractionDigits: 0 })}%
                        </td>
                        <td className="tnum py-1.5 text-end text-text">
                          {formatNumber(locale, simulation.riskAfter - simulation.riskBefore, {
                            maximumFractionDigits: 1,
                          })}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
            </PanelBody>
          </Panel>
        ) : null}

        {/* ── Resilience report ──────────────────────────────────────────── */}
        {kind === 'resilience' && resilience ? (
          <Panel>
            <PanelHeader
              title={t('reports.resilience')}
              subtitle={ar ? resilience.summaryAr : resilience.summary}
            />
            <PanelBody className="pt-0">
              <table className="w-full text-xs">
                <thead>
                  <tr className="border-b border-border text-[10px] uppercase tracking-wide text-text-faint">
                    <th className="py-2 text-start font-medium">{t('resilience.score')}</th>
                    <th className="py-2 text-end font-medium">{t('objective.value')}</th>
                    <th className="py-2 text-end font-medium">{t('objective.normalised')}</th>
                    <th className="py-2 text-end font-medium">{t('objective.weight')}</th>
                  </tr>
                </thead>
                <tbody>
                  {resilience.components.map((component) => (
                    <tr key={component.key} className="border-b border-border/40 last:border-0">
                      <td className="py-1.5 text-text-muted">{t(`resilience.factor.${component.key}`)}</td>
                      <td className="tnum py-1.5 text-end text-text">
                        {formatNumber(locale, component.value, { maximumFractionDigits: 1 })}
                        {component.unit}
                      </td>
                      <td className="tnum py-1.5 text-end text-text-muted">
                        {formatNumber(locale, component.normalised, { maximumFractionDigits: 0 })}
                      </td>
                      <td className="tnum py-1.5 text-end text-text-faint">
                        {formatNumber(locale, component.weight * 100, { maximumFractionDigits: 0 })}%
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </PanelBody>
          </Panel>
        ) : null}

        {/* ── Impact, on every report that has branches (§89) ────────────── */}
        {branches && branches.length > 0 ? (
          <Panel>
            <PanelHeader title={t('futures.title')} subtitle={t('futures.subtitle')} />
            <PanelBody className="pt-0">
              <table className="w-full text-xs">
                <thead>
                  <tr className="border-b border-border text-[10px] uppercase tracking-wide text-text-faint">
                    <th className="py-2 text-start font-medium">{t('futures.title')}</th>
                    <th className="py-2 text-end font-medium">{t('futures.risk')}</th>
                    <th className="py-2 text-end font-medium">{t('futures.assets')}</th>
                    <th className="py-2 text-end font-medium">{t('futures.customers')}</th>
                    <th className="py-2 text-end font-medium">{t('futures.downtime')}</th>
                  </tr>
                </thead>
                <tbody>
                  {branches.map((branch) => (
                    <tr key={branch.key} className="border-b border-border/40 last:border-0">
                      <td className="py-1.5 text-text-muted">{t(`futures.${branch.key}`)}</td>
                      <td className="tnum py-1.5 text-end text-text">
                        {formatNumber(locale, branch.risk, { maximumFractionDigits: 0 })}%
                      </td>
                      <td className="tnum py-1.5 text-end text-text-muted">
                        {formatNumber(locale, branch.assetsAffected)}
                      </td>
                      <td className="tnum py-1.5 text-end text-text-muted">
                        {formatNumber(locale, branch.customersAffected)}
                      </td>
                      <td className="tnum py-1.5 text-end text-text-muted">
                        {formatNumber(locale, branch.potentialDowntimeMin)} {t('common.minutes')}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </PanelBody>
          </Panel>
        ) : null}

        <p className="text-[11px] leading-relaxed text-text-faint">
          {ar
            ? 'كل الأرقام في هذا التقرير محسوبة من محرك المحاكاة في هذه المنصة، وليست نتائج تشغيلية مقيسة.'
            : 'Every figure in this report is computed by this platform’s simulation engine. None of it is a measured operational result.'}
        </p>
      </article>
    </>
  )
}
