import type { Metadata } from 'next'

import { AlertsBoard, EscalationRules, type AlertRow } from '@/components/console/alerts-board'
import { PermissionGate } from '@/components/console/permission-gate'
import { DemoDataBadge, PageHeader, 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: 'Alerts' }
export const dynamic = 'force-dynamic'

export default async function AlertsPage({
  searchParams,
}: {
  searchParams: Promise<{ focus?: string }>
}) {
  const user = await getCurrentUser()
  const { t, locale } = await getI18n()

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

  const [{ focus }, alerts, rules] = await Promise.all([
    searchParams,
    prisma.alert.findMany({
      orderBy: [{ createdAt: 'desc' }],
      take: 150,
      include: {
        asset: { select: { code: true } },
        region: { select: { name: true, nameAr: true } },
        assignedTo: { select: { name: true, nameAr: true } },
        acknowledgedBy: { select: { name: true, nameAr: true } },
        prediction: { select: { code: true } },
      },
    }),
    prisma.escalationRule.findMany({ orderBy: { level: 'asc' } }),
  ])

  const rows: AlertRow[] = alerts.map((alert) => ({
    id: alert.id,
    code: alert.code,
    level: alert.level,
    status: alert.status,
    title: alert.title,
    titleAr: alert.titleAr,
    message: alert.message,
    messageAr: alert.messageAr,
    riskScore: alert.riskScore,
    confidence: alert.confidence,
    expectedAt: alert.expectedAt?.getTime() ?? null,
    createdAt: alert.createdAt.getTime(),
    escalationLevel: alert.escalationLevel,
    channels: alert.channels,
    recommendedAct: alert.recommendedAct,
    recommendedActAr: alert.recommendedActAr,
    resolution: alert.resolution,
    resolutionAr: alert.resolutionAr,
    assetCode: alert.asset?.code ?? null,
    regionName: alert.region?.name ?? null,
    regionNameAr: alert.region?.nameAr ?? null,
    assignedTo: alert.assignedTo
      ? locale === 'ar'
        ? alert.assignedTo.nameAr
        : alert.assignedTo.name
      : null,
    acknowledgedBy: alert.acknowledgedBy
      ? locale === 'ar'
        ? alert.acknowledgedBy.nameAr
        : alert.acknowledgedBy.name
      : null,
    predictionCode: alert.prediction?.code ?? null,
  }))

  const open = rows.filter((row) => !['resolved', 'closed'].includes(row.status))
  const critical = open.filter((row) => ['critical', 'emergency'].includes(row.level))
  const unacknowledged = open.filter((row) => row.status === 'new')

  return (
    <>
      <PageHeader
        title={t('alerts.title')}
        subtitle={t('alerts.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, open.length)}
          state={open.length > 0 ? 'warning' : 'normal'}
        />
        <StatCard
          label={t('alertLevel.critical')}
          value={formatNumber(locale, critical.length)}
          state={critical.length > 0 ? 'critical' : 'normal'}
        />
        <StatCard
          label={t('alertStatus.new')}
          value={formatNumber(locale, unacknowledged.length)}
          state={unacknowledged.length > 0 ? 'watch' : 'normal'}
        />
        <StatCard
          label={t('alertStatus.resolved')}
          value={formatNumber(locale, rows.length - open.length)}
        />
      </div>

      <div className="mt-6 space-y-6">
        <AlertsBoard
          alerts={rows}
          focus={focus}
          canAcknowledge={user.permissions.has('alerts.acknowledge')}
          canResolve={user.permissions.has('alerts.resolve')}
        />
        <EscalationRules rules={rules} />
      </div>
    </>
  )
}
