import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { SimulationTable, type SimulationRow } from '@/components/console/simulation-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: 'Simulations' }
export const dynamic = 'force-dynamic'

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

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

  const simulations = await prisma.simulation.findMany({
    orderBy: { startedAt: 'desc' },
    take: 150,
    include: {
      result: true,
      scenario: { select: { name: true, nameAr: true } },
      createdBy: { select: { name: true, nameAr: true } },
    },
  })

  const rows: SimulationRow[] = simulations.map((simulation) => ({
    id: simulation.id,
    code: simulation.code,
    name: simulation.name,
    nameAr: simulation.nameAr,
    kind: simulation.kind,
    status: simulation.status,
    startedAt: simulation.startedAt.getTime(),
    durationMs: simulation.durationMs,
    appliedActions: simulation.appliedActions,
    createdBy: simulation.createdBy
      ? locale === 'ar'
        ? simulation.createdBy.nameAr
        : simulation.createdBy.name
      : null,
    riskBefore: simulation.result?.riskBefore ?? null,
    riskAfter: simulation.result?.riskAfter ?? null,
    customersImpacted: simulation.result?.customersImpacted ?? null,
    economicImpactSar: simulation.result?.economicImpactSar ?? null,
    verdict: simulation.result?.verdict ?? null,
    verdictAr: simulation.result?.verdictAr ?? null,
  }))

  const preventive = rows.filter((row) => row.kind === 'preventive_action')
  const improved = rows.filter(
    (row) => row.riskBefore !== null && row.riskAfter !== null && row.riskAfter < row.riskBefore,
  )
  const averageReduction = improved.length
    ? improved.reduce((sum, row) => sum + (row.riskBefore! - row.riskAfter!), 0) / improved.length
    : 0

  return (
    <>
      <PageHeader
        title={t('simulations.title')}
        subtitle={t('simulations.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('simulations.title')} value={formatNumber(locale, rows.length)} />
        <StatCard
          label={t('simulations.kind.preventive_action')}
          value={formatNumber(locale, preventive.length)}
        />
        <StatCard
          label={t('recommendations.expectedReduction')}
          value={formatNumber(locale, averageReduction, { maximumFractionDigits: 1 })}
          unit={t('common.units.percent')}
          state="normal"
        />
        <StatCard
          label={t('simulations.kind.what_if')}
          value={formatNumber(locale, rows.filter((row) => row.kind === 'what_if').length)}
        />
      </div>

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