import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { PredictionTable, type PredictionRow } from '@/components/console/prediction-table'
import { DemoDataBadge, PageHeader, Panel, PanelBody, StatCard } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'

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

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

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

  const predictions = await prisma.prediction.findMany({
    orderBy: [{ status: 'asc' }, { riskScore: 'desc' }],
    take: 200,
    include: {
      asset: {
        select: {
          code: true,
          name: true,
          nameAr: true,
          region: { select: { code: true, name: true, nameAr: true } },
        },
      },
      modelVersion: { select: { version: true, key: true } },
      _count: { select: { recommendations: true } },
    },
  })

  const rows: PredictionRow[] = predictions.map((prediction) => ({
    id: prediction.id,
    code: prediction.code,
    assetCode: prediction.asset.code,
    assetName: prediction.asset.name,
    assetNameAr: prediction.asset.nameAr,
    regionName: prediction.asset.region.name,
    regionNameAr: prediction.asset.region.nameAr,
    eventType: prediction.eventType,
    probability: prediction.probability,
    confidence: prediction.confidence,
    severity: prediction.severity,
    riskScore: prediction.riskScore,
    etaMinutes: prediction.etaMinutes,
    etaAt: prediction.etaAt.getTime(),
    status: prediction.status,
    createdAt: prediction.createdAt.getTime(),
    dnaCode: prediction.dnaCode,
    dnaSimilarity: prediction.dnaSimilarity,
    modelVersion: prediction.modelVersion.version,
    recommendationCount: prediction._count.recommendations,
  }))

  const active = rows.filter((row) => row.status === 'active')
  const prevented = rows.filter((row) => row.status === 'prevented')
  const averageConfidence = rows.length
    ? rows.reduce((sum, row) => sum + row.confidence, 0) / rows.length
    : 0

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

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          label={t('predictions.status.active')}
          value={formatNumber(locale, active.length)}
          state={active.length > 0 ? 'warning' : 'normal'}
        />
        <StatCard
          label={t('predictions.status.prevented')}
          value={formatNumber(locale, prevented.length)}
          state="normal"
          hint={t('common.demoEstimate')}
        />
        <StatCard
          label={t('common.confidence')}
          value={formatNumber(locale, averageConfidence * 100, { maximumFractionDigits: 0 })}
          unit="%"
        />
        <StatCard
          label={t('recommendations.title')}
          value={formatNumber(locale, rows.reduce((sum, row) => sum + row.recommendationCount, 0))}
        />
      </div>

      <Panel className="mt-6">
        <PanelBody>
          <PredictionTable rows={rows} />
        </PanelBody>
      </Panel>
    </>
  )
}
