'use client'

import Link from 'next/link'
import { useEffect, useState } from 'react'

import { LiveGridProvider, useLiveGrid } from '@/components/providers/live-grid-provider'
import { useI18n } from '@/components/providers/i18n-provider'
import { Wordmark } from '@/components/brand/logo'
import { NationalMap, type MapAsset, type MapRegion } from '@/components/map/national-map'
import { Badge, Meter, StateBadge } from '@/components/ui/display'
import { cn } from '@/lib/cn'
import { riskToState } from '@/lib/domain/enums'
import { styleForAlertLevel, styleForRisk } from '@/lib/ui/state-styles'
import type { LiveSnapshot } from '@/lib/services/live-snapshot'

interface ControlRoomProps {
  initialSnapshot: LiveSnapshot
  assets: MapAsset[]
  regions: MapRegion[]
  renewables: {
    solarMw: number
    windMw: number
    solarCapacityMw: number
    windCapacityMw: number
    confidenceScore: number
  }
  alerts: Array<{
    code: string
    level: string
    title: string
    titleAr: string
    riskScore: number
    assetCode: string | null
    createdAt: number
  }>
  predictions: Array<{
    code: string
    assetCode: string
    eventType: string
    etaMinutes: number
    probability: number
    riskScore: number
  }>
}

export function ControlRoomView(props: ControlRoomProps) {
  return (
    <LiveGridProvider initial={props.initialSnapshot}>
      <ControlRoomLayout {...props} />
    </LiveGridProvider>
  )
}

function ControlRoomLayout({ assets, regions, renewables, alerts, predictions }: ControlRoomProps) {
  const { t, locale, n, mw, time, relative, duration } = useI18n()
  const { snapshot, status } = useLiveGrid()
  const [clock, setClock] = useState(() => Date.now())

  useEffect(() => {
    const interval = window.setInterval(() => setClock(Date.now()), 1000)
    return () => window.clearInterval(interval)
  }, [])

  const live = snapshot
  const liveAssets = live
    ? assets.map((asset) => {
        const patch = live.topAssets.find((entry) => entry.code === asset.code)
        return patch
          ? { ...asset, risk: patch.risk, state: patch.state, loadPct: patch.loadPct, tempC: patch.tempC }
          : asset
      })
    : assets
  const liveRegions = live
    ? regions.map((region) => {
        const patch = live.regions.find((entry) => entry.code === region.code)
        return patch
          ? { ...region, peakRisk: patch.peakRisk, state: patch.state, loadMw: patch.loadMw }
          : region
      })
    : regions

  const enterFullscreen = () => {
    if (document.fullscreenElement) void document.exitFullscreen()
    else void document.documentElement.requestFullscreen?.()
  }

  return (
    <div className="flex min-h-dvh flex-col bg-base">
      {/* Header strip */}
      <header className="flex flex-wrap items-center justify-between gap-4 border-b border-border px-5 py-3">
        <div className="flex items-center gap-4">
          <Wordmark locale={locale} />
          <span className="hidden text-sm text-text-muted sm:block">{t('controlRoom.title')}</span>
        </div>

        <div className="flex items-center gap-5">
          <span className="tnum text-2xl font-semibold text-text">{time(clock)}</span>
          <span className="flex items-center gap-2 text-xs">
            <span
              className={cn(
                'size-2 rounded-full',
                status === 'live' ? 'bg-brand nabdh-pulse' : 'bg-watch',
              )}
            />
            <span className="text-text-muted">
              {status === 'live' ? t('common.live') : t('common.networkError')}
            </span>
          </span>
          <button
            type="button"
            onClick={enterFullscreen}
            className="rounded-lg border border-border px-3 py-1.5 text-xs text-text-muted transition-colors hover:text-text"
          >
            {t('controlRoom.fullscreen')}
          </button>
          <Link
            href="/command-center"
            className="rounded-lg border border-border px-3 py-1.5 text-xs text-text-muted transition-colors hover:text-text"
          >
            {t('controlRoom.exit')}
          </Link>
        </div>
      </header>

      {/* Headline readouts */}
      <div className="grid gap-px border-b border-border bg-border sm:grid-cols-2 lg:grid-cols-5">
        <BigReadout
          label={t('commandCenter.cards.totalLoad')}
          value={live ? mw(live.totalLoadMw) : '—'}
          unit={t('common.units.mw')}
        />
        <BigReadout
          label={t('commandCenter.frequency')}
          value={
            live ? n(live.frequencyHz, { minimumFractionDigits: 3, maximumFractionDigits: 3 }) : '—'
          }
          unit={t('common.units.hz')}
          alert={live ? Math.abs(live.frequencyHz - 60) > 0.15 : false}
        />
        <BigReadout
          label={t('commandCenter.cards.gridStability')}
          value={live ? n(live.stabilityIndex, { maximumFractionDigits: 1 }) : '—'}
          alert={live ? live.stabilityIndex < 70 : false}
        />
        <BigReadout
          label={t('commandCenter.cards.renewableGeneration')}
          value={live ? mw(live.renewableMw) : '—'}
          unit={t('common.units.mw')}
        />
        <BigReadout
          label={t('commandCenter.cards.criticalAssets')}
          value={live ? n(live.criticalCount) : '—'}
          alert={live ? live.criticalCount > 0 : false}
        />
      </div>

      {/* Main grid */}
      <div className="grid flex-1 gap-px bg-border lg:grid-cols-[1.7fr_1fr]">
        <section className="bg-base p-4">
          <h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-text-faint">
            {t('commandCenter.liveMap')}
          </h2>
          <NationalMap
            assets={liveAssets}
            regions={liveRegions}
            className="h-[calc(100dvh-360px)] min-h-96"
            compact
          />
        </section>

        <div className="grid gap-px bg-border">
          {/* Alerts */}
          <section className="bg-base p-4">
            <h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-text-faint">
              {t('controlRoom.liveAlerts')}
            </h2>
            {alerts.length === 0 ? (
              <p className="text-sm text-text-muted">{t('alerts.emptyAll')}</p>
            ) : (
              <ul className="space-y-1.5">
                {alerts.slice(0, 5).map((alert) => {
                  const style = styleForAlertLevel(alert.level as never)
                  return (
                    <li
                      key={alert.code}
                      className={cn('rounded-lg border px-3 py-2', style.bg, style.border)}
                    >
                      <div className="flex items-center justify-between gap-2">
                        <span className={cn('text-[10px] font-semibold uppercase', style.text)}>
                          {t(`alertLevel.${alert.level}`)}
                        </span>
                        <span className="text-[10px] text-text-faint">
                          {relative(alert.createdAt)}
                        </span>
                      </div>
                      <p className="mt-1 truncate text-sm text-text">
                        {locale === 'ar' ? alert.titleAr : alert.title}
                      </p>
                    </li>
                  )
                })}
              </ul>
            )}
          </section>

          {/* Predictions */}
          <section className="bg-base p-4">
            <h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-text-faint">
              {t('controlRoom.predictions')}
            </h2>
            {predictions.length === 0 ? (
              <p className="text-sm text-text-muted">{t('predictions.empty')}</p>
            ) : (
              <ul className="space-y-1.5">
                {predictions.slice(0, 5).map((prediction) => (
                  <li
                    key={prediction.code}
                    className="flex items-center gap-3 rounded-lg border border-border bg-surface-2/40 px-3 py-2"
                  >
                    <span className="font-mono text-xs text-brand">{prediction.assetCode}</span>
                    <span className="truncate text-xs text-text-muted">
                      {t(`eventType.${prediction.eventType}`)}
                    </span>
                    <span className="ms-auto flex items-center gap-3">
                      <span className="tnum text-[11px] text-text-faint">
                        {duration(prediction.etaMinutes)}
                      </span>
                      <span
                        className={cn(
                          'tnum text-sm font-semibold',
                          styleForRisk(prediction.riskScore).text,
                        )}
                      >
                        {n(prediction.riskScore, { maximumFractionDigits: 0 })}%
                      </span>
                    </span>
                  </li>
                ))}
              </ul>
            )}
          </section>

          {/* Regions */}
          <section className="bg-base p-4">
            <h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-text-faint">
              {t('grid.regionTable')}
            </h2>
            <ul className="space-y-1">
              {[...liveRegions]
                .sort((a, b) => b.peakRisk - a.peakRisk)
                .slice(0, 6)
                .map((region) => (
                  <li key={region.code} className="flex items-center gap-3">
                    <span className="w-24 shrink-0 truncate text-xs text-text">
                      {locale === 'ar' ? region.nameAr : region.name}
                    </span>
                    <Meter
                      value={region.peakRisk}
                      state={riskToState(region.peakRisk)}
                      className="flex-1"
                    />
                    <span className="tnum w-16 shrink-0 text-end text-[11px] text-text-muted">
                      {mw(region.loadMw)}
                    </span>
                    <StateBadge
                      state={region.state}
                      label={t(`states.${region.state}`)}
                      size="sm"
                      className="w-20 justify-center"
                    />
                  </li>
                ))}
            </ul>
          </section>

          {/* Renewables and weather */}
          <section className="bg-base p-4">
            <h2 className="mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-text-faint">
              {t('controlRoom.renewableProduction')}
            </h2>
            <div className="grid gap-3 sm:grid-cols-2">
              <RenewableTile
                label={t('renewables.solar')}
                value={mw(renewables.solarMw)}
                capacity={mw(renewables.solarCapacityMw)}
                unit={t('common.units.mw')}
                ratio={
                  renewables.solarCapacityMw > 0
                    ? (renewables.solarMw / renewables.solarCapacityMw) * 100
                    : 0
                }
              />
              <RenewableTile
                label={t('renewables.wind')}
                value={mw(renewables.windMw)}
                capacity={mw(renewables.windCapacityMw)}
                unit={t('common.units.mw')}
                ratio={
                  renewables.windCapacityMw > 0
                    ? (renewables.windMw / renewables.windCapacityMw) * 100
                    : 0
                }
              />
            </div>

            <div className="mt-3 flex flex-wrap items-center gap-2">
              <Badge tone="info">
                {t('renewables.confidenceScore')}:{' '}
                {n(renewables.confidenceScore, { maximumFractionDigits: 0 })}
              </Badge>
              {live
                ? [...live.regions]
                    .sort((a, b) => b.tempC - a.tempC)
                    .slice(0, 3)
                    .map((region) => (
                      <Badge key={region.code} tone="muted">
                        {region.code} {n(region.tempC, { maximumFractionDigits: 0 })}
                        {t('common.units.celsius')}
                      </Badge>
                    ))
                : null}
            </div>
          </section>
        </div>
      </div>

      <footer className="border-t border-border px-5 py-2">
        <p className="text-center text-[10px] text-text-faint">{t('common.simulatedTooltip')}</p>
      </footer>
    </div>
  )
}

function BigReadout({
  label,
  value,
  unit,
  alert = false,
}: {
  label: string
  value: string
  unit?: string
  alert?: boolean
}) {
  return (
    <div className={cn('bg-base px-5 py-4', alert && 'bg-critical/8')}>
      <p className="text-[10px] uppercase tracking-[0.14em] text-text-faint">{label}</p>
      <p
        className={cn(
          'tnum mt-1 text-3xl font-semibold xl:text-4xl',
          alert ? 'text-critical' : 'text-text',
        )}
      >
        {value}
        {unit ? <span className="ms-2 text-sm font-normal text-text-muted">{unit}</span> : null}
      </p>
    </div>
  )
}

function RenewableTile({
  label,
  value,
  capacity,
  unit,
  ratio,
}: {
  label: string
  value: string
  capacity: string
  unit: string
  ratio: number
}) {
  return (
    <div className="rounded-lg border border-border bg-surface-2/40 px-3.5 py-3">
      <p className="text-[10px] uppercase tracking-wide text-text-faint">{label}</p>
      <p className="tnum mt-1 text-xl font-semibold text-text">
        {value}
        <span className="ms-1 text-[10px] font-normal text-text-muted">{unit}</span>
      </p>
      <p className="tnum mt-0.5 text-[10px] text-text-faint">/ {capacity}</p>
      <Meter value={ratio} className="mt-2" />
    </div>
  )
}
