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

import { PermissionGate } from '@/components/console/permission-gate'
import {
  Badge,
  DemoDataBadge,
  EmptyState,
  PageHeader,
  Panel,
  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, formatNumber } from '@/lib/i18n/translate'
import { styleForSeverity } from '@/lib/ui/state-styles'
import type { Severity } from '@/lib/domain/enums'

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

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

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

  const incidents = await prisma.incident.findMany({
    orderBy: { startedAt: 'desc' },
    include: {
      region: { select: { name: true, nameAr: true } },
      asset: { select: { code: true } },
      _count: { select: { events: true } },
    },
  })

  const prevented = incidents.filter((incident) => incident.wasPrevented)
  const totalCustomers = incidents.reduce((sum, i) => sum + i.customersAffected, 0)
  const leadTimes = incidents.filter((i) => i.nabdhLeadTimeMin > 0)
  const averageLead = leadTimes.length
    ? leadTimes.reduce((sum, i) => sum + i.nabdhLeadTimeMin, 0) / leadTimes.length
    : 0

  return (
    <>
      <PageHeader
        title={t('incidents.title')}
        subtitle={t('incidents.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('incidents.title')} value={formatNumber(locale, incidents.length)} />
        <StatCard
          label={t('incidents.wasPrevented')}
          value={formatNumber(locale, prevented.length)}
          state="normal"
          hint={t('common.demoEstimate')}
        />
        <StatCard
          label={t('incidents.columns.customers')}
          value={formatNumber(locale, totalCustomers)}
        />
        <StatCard
          label={t('incidents.columns.leadTime')}
          value={formatNumber(locale, averageLead, { maximumFractionDigits: 0 })}
          unit={t('common.units.minutes')}
          state="normal"
        />
      </div>

      <Panel className="mt-6">
        <PanelHeader title={t('incidents.title')} subtitle={t('incidents.replay.subtitle')} />
        {incidents.length === 0 ? (
          <EmptyState title={t('incidents.empty')} />
        ) : (
          <ul className="divide-y divide-border">
            {incidents.map((incident) => {
              const style = styleForSeverity(incident.severity as Severity)
              const advantage = incident.nabdhLeadTimeMin - incident.thresholdLeadMin
              return (
                <li key={incident.id}>
                  <Link
                    href={`/incidents/${encodeURIComponent(incident.code)}`}
                    className="flex flex-wrap items-start gap-4 px-4 py-4 transition-colors hover:bg-surface-2/50 sm:px-5"
                  >
                    <div className="min-w-0 flex-1">
                      <div className="flex flex-wrap items-center gap-2">
                        <span className="font-mono text-[11px] text-brand">{incident.code}</span>
                        <span
                          className={`rounded-full border px-2 py-0.5 text-[10px] font-medium ${style.bg} ${style.border} ${style.text}`}
                        >
                          {t(`severity.${incident.severity}`)}
                        </span>
                        {incident.wasPrevented ? (
                          <Badge tone="brand">{t('incidents.wasPrevented')}</Badge>
                        ) : null}
                        {incident.region ? (
                          <span className="text-[11px] text-text-faint">
                            {localised(incident.region, 'name', locale)}
                          </span>
                        ) : null}
                      </div>

                      <h3 className="mt-1.5 text-sm font-medium text-text">
                        {localised(incident, 'title', locale)}
                      </h3>
                      <p className="mt-1 line-clamp-2 text-xs leading-relaxed text-text-muted">
                        {localised(incident, 'description', locale)}
                      </p>
                      <p className="mt-1.5 text-[11px] text-text-faint">
                        {formatDate(locale, incident.startedAt)} ·{' '}
                        {incident.durationMin > 0
                          ? `${formatNumber(locale, incident.durationMin)} ${t('common.units.minutes')}`
                          : t('common.na')}
                        {incident.customersAffected > 0
                          ? ` · ${formatNumber(locale, incident.customersAffected)} ${t('common.units.customers')}`
                          : ''}
                      </p>
                    </div>

                    <div className="shrink-0 text-end">
                      <p className="text-[10px] uppercase tracking-wide text-text-faint">
                        {t('incidents.columns.leadTime')}
                      </p>
                      <p className="tnum text-2xl font-semibold text-brand">
                        {formatNumber(locale, incident.nabdhLeadTimeMin)}
                        <span className="ms-1 text-xs font-normal text-text-muted">
                          {t('common.units.minutes')}
                        </span>
                      </p>
                      {advantage > 0 ? (
                        <p className="tnum mt-0.5 text-[11px] text-text-faint">
                          +{formatNumber(locale, advantage)} {t('common.units.minutes')}
                        </p>
                      ) : null}
                    </div>
                  </Link>
                </li>
              )
            })}
          </ul>
        )}
      </Panel>
    </>
  )
}
