import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { RenewableChart } from '@/components/console/forecast-chart'
import {
  DemoDataBadge,
  KeyValue,
  Meter,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StatCard,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { formatMw, formatNumber, formatTime } from '@/lib/i18n/translate'
import { riskToState } from '@/lib/domain/enums'
import { getRenewableIntelligence } from '@/lib/services/forecast-service'
import { CHART_COLORS } from '@/lib/ui/state-styles'

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

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

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

  const intelligence = await getRenewableIntelligence()
  const { solar, wind } = intelligence

  return (
    <>
      <PageHeader
        title={t('renewables.title')}
        subtitle={t('renewables.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('renewables.current')}
          value={formatMw(locale, intelligence.totalCurrentMw)}
          unit={t('common.units.mw')}
          hint={`${t('renewables.installed')} ${formatMw(locale, intelligence.totalCapacityMw)} ${t('common.units.mw')}`}
          emphasis
        />
        <StatCard
          label={t('renewables.solar')}
          value={formatMw(locale, solar.currentMw)}
          unit={t('common.units.mw')}
          hint={`${t('renewables.capacityFactor')} ${formatNumber(locale, solar.capacityFactor, { maximumFractionDigits: 1 })}%`}
        />
        <StatCard
          label={t('renewables.wind')}
          value={formatMw(locale, wind.currentMw)}
          unit={t('common.units.mw')}
          hint={`${t('renewables.capacityFactor')} ${formatNumber(locale, wind.capacityFactor, { maximumFractionDigits: 1 })}%`}
        />
        <StatCard
          label={t('renewables.confidenceScore')}
          value={formatNumber(locale, intelligence.confidenceScore, { maximumFractionDigits: 0 })}
          state={riskToState(100 - intelligence.confidenceScore)}
          hint={t('renewables.confidenceScoreNote')}
        />
      </div>

      <div className="mt-6 grid gap-6 xl:grid-cols-2">
        {([solar, wind] as const).map((source) => (
          <Panel key={source.kind}>
            <PanelHeader
              title={t(`renewables.${source.kind}`)}
              subtitle={t('renewables.forecastLabel')}
              action={
                <span className="tnum text-sm font-semibold text-text">
                  {formatMw(locale, source.currentMw)}{' '}
                  <span className="text-xs font-normal text-text-muted">
                    {t('common.units.mw')}
                  </span>
                </span>
              }
            />
            <PanelBody className="space-y-4">
              <RenewableChart
                points={source.points}
                capacityMw={source.capacityMw}
                label={t(`renewables.${source.kind}`)}
                color={source.kind === 'solar' ? CHART_COLORS.quaternary : CHART_COLORS.secondary}
              />

              <dl className="grid gap-x-6 sm:grid-cols-2">
                <KeyValue
                  label={t('renewables.installed')}
                  value={`${formatMw(locale, source.capacityMw)} ${t('common.units.mw')}`}
                  mono
                />
                <KeyValue
                  label={t('forecast.expectedPeak')}
                  value={`${formatMw(locale, source.peak.expectedMw)} ${t('common.units.mw')} · ${formatTime(locale, source.peak.ts)}`}
                  mono
                />
                <KeyValue
                  label={t('renewables.expectedVariation')}
                  value={`±${formatMw(locale, source.variabilityMw)} ${t('common.units.mw')}`}
                  mono
                />
                <KeyValue
                  label={t('renewables.confidence')}
                  value={`${formatNumber(locale, source.confidence * 100, { maximumFractionDigits: 0 })}%`}
                  mono
                />
              </dl>

              <Meter
                value={source.capacityFactor}
                state={riskToState(100 - source.capacityFactor)}
                label={t('renewables.capacityFactor')}
                showValue
              />
            </PanelBody>
          </Panel>
        ))}
      </div>

      <Panel className="mt-6">
        <PanelHeader title={t('renewables.byRegion')} subtitle={t('renewables.derateNote')} />
        <PanelBody>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <caption className="sr-only">{t('renewables.byRegion')}</caption>
              <thead>
                <tr className="border-b border-border text-[11px] uppercase tracking-wide text-text-faint">
                  <th scope="col" className="px-3 py-2 text-start">{t('grid.columns.region')}</th>
                  <th scope="col" className="px-3 py-2 text-end">{t('renewables.irradiance')}</th>
                  <th scope="col" className="px-3 py-2 text-end">{t('renewables.windSpeed')}</th>
                  <th scope="col" className="px-3 py-2 text-end">{t('grid.columns.temperature')}</th>
                  <th scope="col" className="px-3 py-2 text-end">{t('renewables.cloudCover')}</th>
                  <th scope="col" className="px-3 py-2 text-end">{t('renewables.dustIndex')}</th>
                  <th scope="col" className="px-3 py-2 text-end">{t('renewables.solar')}</th>
                  <th scope="col" className="px-3 py-2 text-end">{t('renewables.wind')}</th>
                </tr>
              </thead>
              <tbody>
                {intelligence.conditions.map((condition) => (
                  <tr key={condition.code} className="border-b border-border/60">
                    <td className="px-3 py-2.5 text-text">
                      {locale === 'ar' ? condition.nameAr : condition.name}
                    </td>
                    <td className="tnum px-3 py-2.5 text-end text-text-muted">
                      {formatNumber(locale, condition.irradianceWm2)} {t('common.units.wm2')}
                    </td>
                    <td className="tnum px-3 py-2.5 text-end text-text-muted">
                      {formatNumber(locale, condition.windSpeedMs, { maximumFractionDigits: 1 })}{' '}
                      {t('common.units.ms')}
                    </td>
                    <td className="tnum px-3 py-2.5 text-end text-text-muted">
                      {formatNumber(locale, condition.tempC, { maximumFractionDigits: 1 })}
                      {t('common.units.celsius')}
                    </td>
                    <td className="tnum px-3 py-2.5 text-end text-text-muted">
                      {formatNumber(locale, condition.cloudCoverPct)}%
                    </td>
                    <td className="tnum px-3 py-2.5 text-end text-text-muted">
                      {formatNumber(locale, condition.dustIndex, { maximumFractionDigits: 2 })}
                    </td>
                    <td className="tnum px-3 py-2.5 text-end font-medium text-watch">
                      {formatNumber(locale, condition.solarCapacityFactor, { maximumFractionDigits: 0 })}%
                    </td>
                    <td className="tnum px-3 py-2.5 text-end font-medium text-info">
                      {formatNumber(locale, condition.windCapacityFactor, { maximumFractionDigits: 0 })}%
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </PanelBody>
      </Panel>
    </>
  )
}
