import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import {
  Badge,
  EmptyState,
  KeyValue,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StatCard,
} from '@/components/ui/display'
import { Notice } from '@/components/ui/controls'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { formatDateTime, formatNumber } from '@/lib/i18n/translate'
import {
  assessModelDrift,
  listDriftEvents,
  listModelAudit,
  listModels,
} from '@/lib/services/governance-service'
import { cn } from '@/lib/cn'

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

const SEVERITY_TONE: Record<string, 'brand' | 'info' | 'accent' | 'muted'> = {
  info: 'muted',
  watch: 'info',
  review_recommended: 'accent',
}

const STATUS_TONE: Record<string, 'brand' | 'info' | 'accent' | 'muted'> = {
  active: 'brand',
  approved: 'info',
  validation: 'info',
  staging: 'info',
  draft: 'muted',
  retired: 'muted',
}

/**
 * AI governance (§81, §82, §83).
 *
 * The point of this page is not to show that the models are good. It is to show that
 * somebody would notice if they stopped being good — a different and much more checkable
 * claim, and the reason the drift comparison leads with its sample counts.
 */
export default async function GovernancePage() {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('governance.read')) return <PermissionGate />

  const [models, drift, events, audit] = await Promise.all([
    listModels(),
    assessModelDrift({}),
    listDriftEvents({ limit: 12 }),
    listModelAudit(15),
  ])

  const num = (value: number, digits = 1) =>
    formatNumber(locale, value, { maximumFractionDigits: digits })

  return (
    <>
      <PageHeader title={t('governance.title')} subtitle={t('governance.subtitle')} />

      <div className="space-y-4">
        <Notice tone="info">{t('governance.noAutoDeploy')}</Notice>

        {/* ── Drift ─────────────────────────────────────────────────────────── */}
        <Panel>
          <PanelHeader
            title={t('governance.drift')}
            subtitle={t('governance.driftSubtitle')}
            action={
              <Badge tone={drift.verdict.reviewRecommended ? 'accent' : 'brand'} dot>
                {drift.verdict.reviewRecommended
                  ? t('governance.reviewRecommended')
                  : t('governance.noDrift')}
              </Badge>
            }
          />
          <PanelBody className="space-y-3">
            {drift.underpowered ? (
              <Notice tone="warning">{t('governance.underpowered')}</Notice>
            ) : null}

            <div className="grid gap-3 sm:grid-cols-3">
              <StatCard
                label={t('governance.reliability')}
                value={`${num(drift.verdict.reliability)}%`}
              />
              <StatCard
                label={t('governance.baselineWindow')}
                value={`${drift.baselineWindow.sampleCount} ${t('governance.samples')}`}
                hint={formatDateTime(locale, drift.baselineWindow.fromTs)}
              />
              <StatCard
                label={t('governance.recentWindow')}
                value={`${drift.recentWindow.sampleCount} ${t('governance.samples')}`}
                hint={formatDateTime(locale, drift.recentWindow.fromTs)}
              />
            </div>

            <ul className="space-y-1.5">
              {drift.verdict.signals.map((signal) => (
                <li
                  key={signal.metricKey}
                  className={cn(
                    'min-w-0 rounded-lg border px-3 py-2',
                    signal.severity === 'review_recommended'
                      ? 'border-accent/30 bg-accent/8'
                      : signal.severity === 'watch'
                        ? 'border-info/30 bg-info/8'
                        : 'border-border bg-surface-2/40',
                  )}
                >
                  <div className="flex flex-wrap items-baseline justify-between gap-2">
                    <span className="text-[11px] font-medium">
                      {locale === 'ar' ? signal.labelAr : signal.label}
                    </span>
                    <span className="flex shrink-0 items-center gap-2">
                      <Badge tone={SEVERITY_TONE[signal.severity] ?? 'muted'}>
                        {t(`governance.kind.${signal.kind}`)}
                      </Badge>
                      <span
                        className={cn(
                          'font-mono text-[11px] tabular-nums',
                          Math.abs(signal.deltaPct) >= signal.threshold
                            ? 'text-warning'
                            : 'text-text-faint',
                        )}
                      >
                        {signal.deltaPct >= 0 ? '+' : ''}
                        {num(signal.deltaPct, 2)}%
                      </span>
                    </span>
                  </div>
                  <p className="mt-0.5 text-[10px] leading-relaxed text-text-faint">
                    {locale === 'ar' ? signal.detailAr : signal.detail}
                  </p>
                </li>
              ))}
            </ul>
          </PanelBody>
        </Panel>

        {/* ── Models ────────────────────────────────────────────────────────── */}
        <Panel>
          <PanelHeader title={t('governance.models')} />
          <PanelBody>
            <div className="overflow-x-auto">
              <table className="w-full min-w-[38rem] text-[11px]">
                <thead>
                  <tr className="text-text-faint">
                    <th className="py-1.5 text-start font-medium">{t('models.columns.name')}</th>
                    <th className="py-1.5 text-start font-medium">{t('models.columns.version')}</th>
                    <th className="py-1.5 text-start font-medium">{t('models.columns.status')}</th>
                    <th className="py-1.5 text-end font-medium">{t('models.columns.accuracy')}</th>
                    <th className="py-1.5 text-end font-medium">{t('models.columns.trained')}</th>
                  </tr>
                </thead>
                <tbody>
                  {models.map((model) => (
                    <tr key={model.id} className="border-t border-border/60">
                      <td className="py-1.5">{model.name}</td>
                      <td className="py-1.5 font-mono text-text-muted">{model.version}</td>
                      <td className="py-1.5">
                        <Badge tone={STATUS_TONE[model.status] ?? 'muted'}>{model.status}</Badge>
                        {model.driftOpen > 0 ? (
                          <span className="ms-1.5 text-[10px] text-accent">
                            {model.driftOpen} {t('governance.drift').toLowerCase()}
                          </span>
                        ) : null}
                      </td>
                      <td className="py-1.5 text-end font-mono tabular-nums">
                        {num(model.accuracy * 100)}%
                      </td>
                      <td className="py-1.5 text-end text-text-faint">
                        {formatDateTime(locale, model.trainedAt)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </PanelBody>
        </Panel>

        <div className="grid gap-4 xl:grid-cols-2">
          {/* ── Recorded drift events ─────────────────────────────────────────── */}
          <div className="min-w-0">
            <Panel>
              <PanelHeader title={t('governance.drift')} />
              <PanelBody>
                {events.length === 0 ? (
                  <EmptyState title={t('uiState.empty')} body={t('governance.noDrift')} />
                ) : (
                  <ul className="space-y-1.5">
                    {events.map((event) => (
                      <li key={event.id} className="min-w-0 rounded-lg border border-border px-3 py-2">
                        <div className="flex flex-wrap items-baseline justify-between gap-2 text-[11px]">
                          <span className="font-medium">{event.modelKey}</span>
                          <Badge tone={SEVERITY_TONE[event.severity] ?? 'muted'}>
                            {t(`governance.severity.${event.severity}`)}
                          </Badge>
                        </div>
                        <p className="mt-0.5 text-[10px] leading-relaxed text-text-faint">
                          {locale === 'ar' ? event.detailAr : event.detail}
                        </p>
                      </li>
                    ))}
                  </ul>
                )}
              </PanelBody>
            </Panel>
          </div>

          {/* ── Change log (§83) ──────────────────────────────────────────────── */}
          <div className="min-w-0">
            <Panel>
              <PanelHeader title={t('governance.changeLog')} />
              <PanelBody>
                {audit.length === 0 ? (
                  <EmptyState title={t('uiState.empty')} body={t('governance.lifecycle')} />
                ) : (
                  <ul className="space-y-1.5">
                    {audit.map((entry) => (
                      <li key={entry.id} className="min-w-0 text-[11px]">
                        <KeyValue
                          label={`${entry.modelVersion.name} ${entry.modelVersion.version}`}
                          value={
                            <span className="text-text-muted">
                              {entry.action} · {formatDateTime(locale, entry.ts.getTime())}
                            </span>
                          }
                        />
                      </li>
                    ))}
                  </ul>
                )}
              </PanelBody>
            </Panel>
          </div>
        </div>
      </div>
    </>
  )
}
