import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import {
  Badge,
  DemoDataBadge,
  Meter,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StatCard,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { getI18n } from '@/lib/i18n/server'
import { formatDateTime, formatNumber } from '@/lib/i18n/translate'
import { getCalibration } from '@/lib/services/twin-service'
import { listDecisions, storedConfidence } from '@/lib/services/decision-service'
import { MAX_AUTONOMY_LEVEL } from '@/lib/domain/provenance'
import { cn } from '@/lib/cn'

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

/**
 * The trust centre (§83–§85, §92).
 *
 * Everything a sceptical reader would want before believing a number on any other page:
 * what the models are, how well the twin has tracked reality, how much of the data is
 * measured, what has been decided and by whom, and exactly how much autonomy the software
 * has. The most important line on the page is the one saying no model was trained.
 */
export default async function TrustPage() {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()
  if (!user?.permissions.has('models.read')) return <PermissionGate />

  const [models, quality, sensorTrust, calibration, decisions] = await Promise.all([
    prisma.modelVersion.findMany({ orderBy: { trainedAt: 'desc' }, take: 8 }),
    prisma.dataQualityScore.aggregate({ _avg: { score: true }, _count: true }),
    prisma.sensorTrustScore.aggregate({ _avg: { score: true }, _count: true }),
    getCalibration('TWIN-NATIONAL'),
    listDecisions({ limit: 8 }),
  ])

  const dataScore = quality._avg.score ?? 0
  const trustScore = sensorTrust._avg.score ?? 0

  return (
    <>
      <PageHeader
        title={t('trust.title')}
        subtitle={t('trust.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
      />

      <Panel glow>
        <PanelHeader title={t('trust.autonomy')} subtitle={t('twin.autonomyNote')} />
        <PanelBody className="pt-0">
          <ol className="flex flex-wrap gap-2">
            {[0, 1, 2, 3, 4].map((level) => (
              <li
                key={level}
                className={cn(
                  'rounded-full border px-3 py-1 text-[11px] font-medium',
                  level < MAX_AUTONOMY_LEVEL
                    ? 'border-normal/35 bg-normal/8 text-normal'
                    : level === MAX_AUTONOMY_LEVEL
                      ? 'border-brand/45 bg-brand/10 text-brand'
                      : 'border-border bg-surface-2 text-text-faint line-through',
                )}
              >
                {t(`twin.autonomyLevel.${level}`)}
              </li>
            ))}
          </ol>
        </PanelBody>
      </Panel>

      <div className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          label={t('trust.dataQuality')}
          value={formatNumber(locale, dataScore, { maximumFractionDigits: 0 })}
          unit="%"
          hint={`${formatNumber(locale, quality._count)} ${t('assets.title').toLowerCase()}`}
          state={dataScore >= 85 ? 'normal' : dataScore >= 65 ? 'watch' : 'critical'}
        />
        <StatCard
          label={t('twin.sensorTrust')}
          value={formatNumber(locale, trustScore, { maximumFractionDigits: 0 })}
          unit="%"
          hint={`${formatNumber(locale, sensorTrust._count)} ${t('twin.sensors').toLowerCase()}`}
        />
        <StatCard
          label={t('trust.calibration')}
          value={
            calibration ? formatNumber(locale, calibration.meanAbsPct, { maximumFractionDigits: 1 }) : '—'
          }
          unit="%"
          hint={calibration ? t(`trust.driftState.${calibration.drift}`) : undefined}
          state={
            calibration && calibration.drift === 'stable'
              ? 'normal'
              : calibration && calibration.drift === 'drifting'
                ? 'watch'
                : 'critical'
          }
        />
        <StatCard label={t('trust.models')} value={formatNumber(locale, models.length)} />
      </div>

      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <Panel>
          <PanelHeader title={t('trust.calibration')} subtitle={t('trust.calibrationHint')} />
          <PanelBody className="pt-0">
            {!calibration || calibration.samples === 0 ? (
              <p className="py-2 text-xs text-text-muted">{t('uiState.empty')}</p>
            ) : (
              <>
                <div className="overflow-x-auto">
                  <table className="w-full min-w-[24rem] text-[11px]">
                    <thead>
                      <tr className="border-b border-border text-[10px] uppercase tracking-wide text-text-faint">
                        <th className="py-1.5 text-start font-medium">{t('weakSignals.channel')}</th>
                        <th className="py-1.5 text-end font-medium">{t('trust.meanError')}</th>
                        <th className="py-1.5 text-end font-medium">{t('trust.bias')}</th>
                        <th className="py-1.5 text-end font-medium">{t('common.simulated')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {calibration.perChannel.map((channel) => (
                        <tr key={channel.channel} className="border-b border-border/40 last:border-0">
                          <td className="py-1.5 text-text-muted">{channel.channel}</td>
                          <td className="tnum py-1.5 text-end text-text">
                            {formatNumber(locale, channel.meanAbsError, { maximumFractionDigits: 2 })}
                          </td>
                          <td
                            className={cn(
                              'tnum py-1.5 text-end',
                              Math.abs(channel.meanBiasPct) > 8 ? 'text-watch' : 'text-text-muted',
                            )}
                          >
                            {channel.meanBiasPct > 0 ? '+' : ''}
                            {formatNumber(locale, channel.meanBiasPct, { maximumFractionDigits: 2 })}%
                          </td>
                          <td className="tnum py-1.5 text-end text-text-faint">
                            {formatNumber(locale, channel.samples)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <p className="mt-3 rounded-lg border border-border bg-surface-2/40 px-3 py-2 text-[11px] leading-relaxed text-text-muted">
                  {locale === 'ar' ? calibration.recommendationAr : calibration.recommendation}
                </p>
              </>
            )}
          </PanelBody>
        </Panel>

        <Panel>
          <PanelHeader
            title={t('trust.models')}
            subtitle={t('trust.noModel')}
            action={<Badge tone="accent">{t('source.synthetic')}</Badge>}
          />
          <PanelBody className="pt-0">
            <ul className="divide-y divide-border/60">
              {models.map((model) => (
                <li key={model.id} className="py-2">
                  <div className="flex flex-wrap items-baseline justify-between gap-2">
                    <span className="text-[11px] font-medium text-text">
                      {locale === 'ar' ? model.nameAr : model.name}
                    </span>
                    <span className="font-mono text-[10px] text-text-faint">{model.version}</span>
                  </div>
                  <div className="mt-1 flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-text-muted">
                    <span className="tnum">
                      {t('models.columns.accuracy')}{' '}
                      {formatNumber(locale, model.accuracy * 100, { maximumFractionDigits: 1 })}%
                    </span>
                    <span className="tnum">
                      {t('trust.drift')} {formatNumber(locale, model.driftScore, { maximumFractionDigits: 3 })}
                    </span>
                    <span>{model.driftStatus}</span>
                  </div>
                  <Meter className="mt-1.5" value={model.accuracy * 100} state="normal" />
                </li>
              ))}
            </ul>
          </PanelBody>
        </Panel>
      </div>

      <Panel className="mt-6">
        <PanelHeader title={t('trust.decisions')} subtitle={t('decisions.workflow')} />
        <PanelBody className="pt-0">
          {decisions.length === 0 ? (
            <p className="py-2 text-xs text-text-muted">{t('decisions.empty')}</p>
          ) : (
            <ul className="divide-y divide-border/60">
              {decisions.map((decision) => {
                const confidence = storedConfidence(decision)
                return (
                  <li key={decision.code} className="flex flex-wrap items-baseline justify-between gap-3 py-2">
                    <div className="min-w-0">
                      <p className="text-[11px] font-medium text-text">
                        {locale === 'ar' ? decision.titleAr : decision.title}
                      </p>
                      <p className="tnum mt-0.5 text-[10px] text-text-faint">
                        {decision.code} · {formatDateTime(locale, decision.createdAt.getTime())}
                      </p>
                    </div>
                    <div className="flex shrink-0 items-center gap-3">
                      <span className="tnum text-[11px] text-text-muted">
                        {t('confidence.overall')}{' '}
                        {formatNumber(locale, confidence.overall, { maximumFractionDigits: 0 })}%
                      </span>
                      <Badge tone="muted">{t(`decisions.status.${decision.status}`)}</Badge>
                    </div>
                  </li>
                )
              })}
            </ul>
          )}
        </PanelBody>
      </Panel>
    </>
  )
}
