import type { Metadata } from 'next'
import { redirect } from 'next/navigation'

import { ControlRoomView } from '@/components/console/control-room'
import { Wordmark } from '@/components/brand/logo'
import { ErrorState, LinkButton } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { prisma } from '@/lib/db'
import { getMapData } from '@/lib/services/map-service'
import { buildLiveSnapshot } from '@/lib/services/live-snapshot'
import { getRenewableIntelligence } from '@/lib/services/forecast-service'

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

/**
 * Control Room mode (§23).
 *
 * Built for a wall display rather than a desk: no navigation, larger type, and every
 * panel fed by the same live stream so the whole screen advances on one tick. Nothing
 * here is interactive beyond the map, because nobody clicks a wall.
 */
export default async function ControlRoomPage() {
  const user = await getCurrentUser()
  if (!user) redirect('/login?next=/control-room')

  const { t, locale } = await getI18n()

  if (!user.permissions.has('presentation.use')) {
    return (
      <div className="flex min-h-dvh flex-col items-center justify-center gap-6 px-4">
        <Wordmark locale={locale} />
        <ErrorState
          title={t('common.permissionDenied')}
          body={t('common.permissionDeniedBody')}
          action={
            <LinkButton href="/command-center" variant="secondary" size="sm">
              {t('common.back')}
            </LinkButton>
          }
        />
      </div>
    )
  }

  const [snapshot, mapData, renewables, alerts, predictions] = await Promise.all([
    buildLiveSnapshot(),
    getMapData(),
    getRenewableIntelligence(360),
    prisma.alert.findMany({
      where: { status: { in: ['new', 'acknowledged', 'in_progress'] } },
      orderBy: [{ riskScore: 'desc' }],
      take: 8,
      include: { asset: { select: { code: true } } },
    }),
    prisma.prediction.findMany({
      where: { status: 'active' },
      orderBy: { riskScore: 'desc' },
      take: 6,
      include: { asset: { select: { code: true } } },
    }),
  ])

  return (
    <ControlRoomView
      initialSnapshot={snapshot}
      assets={mapData.assets}
      regions={mapData.regions}
      renewables={{
        solarMw: renewables.solar.currentMw,
        windMw: renewables.wind.currentMw,
        solarCapacityMw: renewables.solar.capacityMw,
        windCapacityMw: renewables.wind.capacityMw,
        confidenceScore: renewables.confidenceScore,
      }}
      alerts={alerts.map((alert) => ({
        code: alert.code,
        level: alert.level,
        title: alert.title,
        titleAr: alert.titleAr,
        riskScore: alert.riskScore,
        assetCode: alert.asset?.code ?? null,
        createdAt: alert.createdAt.getTime(),
      }))}
      predictions={predictions.map((prediction) => ({
        code: prediction.code,
        assetCode: prediction.asset.code,
        eventType: prediction.eventType,
        etaMinutes: prediction.etaMinutes,
        probability: prediction.probability,
        riskScore: prediction.riskScore,
      }))}
    />
  )
}
