import type { Metadata } from 'next'
import Link from 'next/link'
import { notFound } from 'next/navigation'

import { IncidentReplay, type ReplayFrame } from '@/components/console/incident-replay'
import { PermissionGate } from '@/components/console/permission-gate'
import {
  Badge,
  DemoDataBadge,
  KeyValue,
  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 { formatDateTime, formatNumber } from '@/lib/i18n/translate'

export const dynamic = 'force-dynamic'

export async function generateMetadata({
  params,
}: {
  params: Promise<{ code: string }>
}): Promise<Metadata> {
  const { code } = await params
  return { title: decodeURIComponent(code) }
}

export default async function IncidentPage({ params }: { params: Promise<{ code: string }> }) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()

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

  const { code } = await params
  const incident = await prisma.incident.findUnique({
    where: { code: decodeURIComponent(code) },
    include: {
      region: { select: { name: true, nameAr: true } },
      asset: { select: { code: true, name: true, nameAr: true } },
      events: { orderBy: { offsetMin: 'asc' } },
    },
  })

  if (!incident) notFound()

  const frames: ReplayFrame[] = incident.events.map((event) => ({
    ts: event.ts.getTime(),
    offsetMin: event.offsetMin,
    phase: event.phase,
    label: event.label,
    labelAr: event.labelAr,
    loadPct: event.loadPct,
    tempC: event.tempC,
    voltageKv: event.voltageKv,
    frequencyHz: event.frequencyHz,
    riskScore: event.riskScore,
    marker: event.marker,
    note: event.note,
    noteAr: event.noteAr,
  }))

  return (
    <>
      <PageHeader
        title={`${incident.code} · ${localised(incident, 'title', locale)}`}
        subtitle={localised(incident, 'description', locale)}
        badge={
          <div className="flex flex-wrap items-center gap-2">
            <Badge tone={incident.wasPrevented ? 'brand' : 'neutral'}>
              {incident.wasPrevented ? t('incidents.wasPrevented') : t(`severity.${incident.severity}`)}
            </Badge>
            <DemoDataBadge label={t('common.simulated')} />
          </div>
        }
        action={
          <Link href="/incidents" className="text-xs font-medium text-brand hover:underline">
            ← {t('incidents.title')}
          </Link>
        }
      />

      <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <StatCard
          label={t('incidents.columns.duration')}
          value={formatNumber(locale, incident.durationMin)}
          unit={t('common.units.minutes')}
        />
        <StatCard
          label={t('incidents.columns.customers')}
          value={formatNumber(locale, incident.customersAffected)}
          state={incident.customersAffected > 0 ? 'warning' : 'normal'}
        />
        <StatCard
          label={t('incidents.columns.energy')}
          value={formatNumber(locale, incident.energyNotServedMwh, { maximumFractionDigits: 1 })}
          unit={t('common.units.mwh')}
        />
        <StatCard
          label={t('incidents.economicImpact')}
          value={formatNumber(locale, incident.economicImpactSar, { maximumFractionDigits: 0 })}
          unit={t('common.units.sar')}
          hint={t('common.demoEstimate')}
        />
      </div>

      {frames.length > 0 ? (
        <div className="mt-6">
          <IncidentReplay
            frames={frames}
            nabdhLeadTimeMin={incident.nabdhLeadTimeMin}
            thresholdLeadMin={incident.thresholdLeadMin}
            wasPrevented={incident.wasPrevented}
          />
        </div>
      ) : null}

      <Panel className="mt-6">
        <PanelHeader title={t('incidents.rootCause')} />
        <PanelBody>
          <p className="text-sm leading-relaxed text-text">
            {localised(incident, 'rootCause', locale)}
          </p>

          <dl className="mt-5 grid gap-x-8 gap-y-1 border-t border-border pt-4 sm:grid-cols-2 lg:grid-cols-3">
            <KeyValue
              label={t('incidents.columns.started')}
              value={formatDateTime(locale, incident.startedAt)}
            />
            {incident.endedAt ? (
              <KeyValue
                label={t('common.updated')}
                value={formatDateTime(locale, incident.endedAt)}
              />
            ) : null}
            {incident.region ? (
              <KeyValue
                label={t('common.region')}
                value={localised(incident.region, 'name', locale)}
              />
            ) : null}
            {incident.asset ? (
              <KeyValue
                label={t('common.asset')}
                value={
                  <Link
                    href={`/assets/${encodeURIComponent(incident.asset.code)}`}
                    className="text-brand hover:underline"
                  >
                    {incident.asset.code}
                  </Link>
                }
              />
            ) : null}
            <KeyValue label={t('common.severity')} value={t(`severity.${incident.severity}`)} />
            <KeyValue label={t('common.status')} value={t(`alertStatus.${incident.status}`)} />
          </dl>
        </PanelBody>
      </Panel>
    </>
  )
}
