'use client'

import Link from 'next/link'

import { useI18n } from '@/components/providers/i18n-provider'
import { useLiveGrid } from '@/components/providers/live-grid-provider'
import { DataTable, type Column } from '@/components/ui/data-table'
import { Meter, StateBadge } from '@/components/ui/display'
import { riskToState, type GridState } from '@/lib/domain/enums'
import { styleForRisk } from '@/lib/ui/state-styles'

export interface RegionRow {
  code: string
  name: string
  nameAr: string
  loadMw: number
  capacityMw: number
  reserveMarginPct: number
  renewableMw: number
  renewableSharePct: number
  peakRisk: number
  averageRisk: number
  state: GridState
  assetCount: number
  assetsAtRisk: number
  averageHealth: number
  tempC: number
}

/** The regional balance table, patched from the live stream on every tick. */
export function RegionTable({ regions }: { regions: RegionRow[] }) {
  const { t, locale, n, mw } = useI18n()
  const { snapshot } = useLiveGrid()

  const live = snapshot
    ? regions.map((region) => {
        const patch = snapshot.regions.find((entry) => entry.code === region.code)
        return patch
          ? {
              ...region,
              loadMw: patch.loadMw,
              peakRisk: patch.peakRisk,
              state: patch.state,
              tempC: patch.tempC,
              renewableMw: patch.renewableMw,
            }
          : region
      })
    : regions

  const columns: Array<Column<RegionRow>> = [
    {
      key: 'region',
      header: t('grid.columns.region'),
      sortValue: (row) => (locale === 'ar' ? row.nameAr : row.name),
      cell: (row) => (
        <Link
          href={`/map?region=${row.code}`}
          className="font-medium text-text transition-colors hover:text-brand"
        >
          {locale === 'ar' ? row.nameAr : row.name}
          <span className="ms-2 font-mono text-[10px] text-text-faint">{row.code}</span>
        </Link>
      ),
    },
    {
      key: 'load',
      header: t('grid.columns.load'),
      align: 'end',
      sortValue: (row) => row.loadMw,
      cell: (row) => <span className="tnum">{mw(row.loadMw)}</span>,
    },
    {
      key: 'capacity',
      header: t('grid.columns.capacity'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.capacityMw,
      cell: (row) => <span className="tnum text-text-muted">{mw(row.capacityMw)}</span>,
    },
    {
      key: 'reserve',
      header: t('grid.columns.reserve'),
      align: 'end',
      sortValue: (row) => row.reserveMarginPct,
      cell: (row) => (
        <span
          className={`tnum ${row.reserveMarginPct < 12 ? 'text-warning' : 'text-text-muted'}`}
        >
          {n(row.reserveMarginPct, { maximumFractionDigits: 1 })}%
        </span>
      ),
    },
    {
      key: 'renewables',
      header: t('grid.columns.renewables'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.renewableMw,
      cell: (row) => (
        <span className="tnum text-text-muted">
          {mw(row.renewableMw)}
          <span className="ms-1 text-[10px]">
            ({n(row.renewableSharePct, { maximumFractionDigits: 0 })}%)
          </span>
        </span>
      ),
    },
    {
      key: 'temperature',
      header: t('grid.columns.temperature'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.tempC,
      cell: (row) => (
        <span className="tnum text-text-muted">
          {n(row.tempC, { maximumFractionDigits: 1 })}
          {t('common.units.celsius')}
        </span>
      ),
    },
    {
      key: 'assets',
      header: t('grid.columns.atRisk'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.assetsAtRisk,
      cell: (row) => (
        <span className="tnum text-text-muted">
          {n(row.assetsAtRisk)} / {n(row.assetCount)}
        </span>
      ),
    },
    {
      key: 'peakRisk',
      header: t('grid.columns.peakRisk'),
      align: 'end',
      sortValue: (row) => row.peakRisk,
      cell: (row) => (
        <div className="flex items-center justify-end gap-2">
          <Meter value={row.peakRisk} state={riskToState(row.peakRisk)} className="w-16" />
          <span className={`tnum w-10 text-end font-medium ${styleForRisk(row.peakRisk).text}`}>
            {n(row.peakRisk, { maximumFractionDigits: 0 })}%
          </span>
        </div>
      ),
    },
    {
      key: 'state',
      header: t('grid.columns.state'),
      align: 'end',
      sortValue: (row) => row.peakRisk,
      cell: (row) => (
        <StateBadge
          state={row.state}
          label={t(`states.${row.state}`)}
          size="sm"
          pulse={row.peakRisk >= 75}
        />
      ),
    },
  ]

  return (
    <DataTable
      rows={live}
      columns={columns}
      getRowKey={(row) => row.code}
      initialSort={{ key: 'peakRisk', direction: 'desc' }}
      pageSize={12}
      caption={t('grid.regionTable')}
    />
  )
}
