import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import {
  Badge,
  DemoDataBadge,
  KeyValue,
  Meter,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StatCard,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { getI18n, localised } from '@/lib/i18n/server'
import { formatDate, formatDateTime, formatNumber } from '@/lib/i18n/translate'

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

export default async function ModelsPage() {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()

  if (!user?.permissions.has('models.read')) return <PermissionGate />

  const models = await prisma.modelVersion.findMany({
    orderBy: [{ status: 'asc' }, { key: 'asc' }],
    include: { audits: { orderBy: { ts: 'desc' }, take: 3 } },
  })

  const active = models.filter((model) => model.status === 'active')
  const averageF1 = active.length
    ? active.reduce((sum, model) => sum + model.f1Score, 0) / active.length
    : 0
  const drifting = models.filter((model) => model.driftStatus !== 'stable').length

  return (
    <>
      <PageHeader
        title={t('models.title')}
        subtitle={t('models.subtitle')}
        badge={<DemoDataBadge label={t('common.simulatedFull')} title={t('models.honestyNote')} />}
      />

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard label={t('models.status.active')} value={formatNumber(locale, active.length)} />
        <StatCard label={t('models.title')} value={formatNumber(locale, models.length)} />
        <StatCard
          label={t('models.columns.f1')}
          value={formatNumber(locale, averageF1 * 100, { maximumFractionDigits: 1 })}
          unit="%"
        />
        <StatCard
          label={t('models.columns.drift')}
          value={formatNumber(locale, drifting)}
          state={drifting > 0 ? 'watch' : 'normal'}
        />
      </div>

      <div className="mt-6 rounded-[--radius-panel] border border-watch/25 bg-watch/8 px-4 py-3">
        <p className="text-xs leading-relaxed text-watch">{t('models.honestyNote')}</p>
      </div>

      <div className="mt-6 space-y-4">
        {models.map((model) => (
          <Panel key={model.id}>
            <PanelHeader
              title={`${localised(model, 'name', locale)} · ${model.version}`}
              subtitle={model.algorithm}
              action={
                <div className="flex flex-wrap items-center gap-2">
                  <Badge tone={model.status === 'active' ? 'brand' : 'muted'}>
                    {t(`models.status.${model.status}`)}
                  </Badge>
                  <Badge tone={model.driftStatus === 'stable' ? 'muted' : 'info'}>
                    {t(`models.driftStatus.${model.driftStatus}`)}
                  </Badge>
                </div>
              }
            />
            <PanelBody className="space-y-4">
              <div className="grid gap-6 lg:grid-cols-[1.2fr_1fr]">
                <div className="space-y-3">
                  {(
                    [
                      ['accuracy', model.accuracy],
                      ['precision', model.precisionScore],
                      ['recall', model.recallScore],
                      ['f1', model.f1Score],
                    ] as const
                  ).map(([key, value]) => (
                    <div key={key}>
                      <div className="mb-1 flex items-baseline justify-between">
                        <span className="text-xs text-text-muted">{t(`models.columns.${key}`)}</span>
                        <span className="tnum text-xs font-medium text-text">
                          {formatNumber(locale, value * 100, { maximumFractionDigits: 1 })}%
                        </span>
                      </div>
                      <Meter value={value * 100} state="normal" />
                    </div>
                  ))}
                </div>

                <dl className="divide-y divide-border/60">
                  <KeyValue label={t('models.columns.task')} value={model.task} />
                  <KeyValue
                    label={t('models.columns.trained')}
                    value={formatDate(locale, model.trainedAt)}
                  />
                  <KeyValue label={t('models.columns.dataset')} value={model.datasetVersion} mono />
                  <KeyValue
                    label={t('models.columns.drift')}
                    value={formatNumber(locale, model.driftScore, { maximumFractionDigits: 3 })}
                    mono
                  />
                </dl>
              </div>

              <p className="rounded-lg border border-border bg-surface-2/50 px-3.5 py-2.5 text-xs leading-relaxed text-text-muted">
                {localised(model, 'notes', locale)}
              </p>

              <div>
                <p className="mb-2 text-[10px] font-semibold uppercase tracking-wide text-text-faint">
                  {t('models.auditTrail')}
                </p>
                <ul className="space-y-1.5">
                  {model.audits.map((audit) => (
                    <li
                      key={audit.id}
                      className="flex flex-wrap items-center gap-3 rounded-lg border border-border bg-surface-2/40 px-3 py-2 text-xs"
                    >
                      <span className="font-mono text-[11px] text-text-faint">
                        {formatDateTime(locale, audit.ts)}
                      </span>
                      <Badge tone="muted">{audit.action}</Badge>
                      <span className="text-text-muted">{localised(audit, 'detail', locale)}</span>
                      <span className="ms-auto text-[11px] text-text-faint">{audit.actor}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </PanelBody>
          </Panel>
        ))}
      </div>
    </>
  )
}
