'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 { ASSET_TYPE_KEYS, CRITICALITIES, GRID_STATES, type GridState } from '@/lib/domain/enums'
import { styleForHealth, styleForRisk } from '@/lib/ui/state-styles'

export interface AssetRow {
  code: string
  name: string
  nameAr: string
  typeKey: string
  regionCode: string
  regionName: string
  regionNameAr: string
  capacityMw: number
  loadPct: number
  tempC: number
  ratedTempC: number
  health: number
  risk: number
  state: GridState
  status: string
  criticality: string
}

export function AssetTable({ rows }: { rows: AssetRow[] }) {
  const { t, locale, n, mw } = useI18n()
  const { snapshot } = useLiveGrid()

  const live = snapshot
    ? rows.map((row) => {
        const patch = snapshot.topAssets.find((asset) => asset.code === row.code)
        return patch
          ? { ...row, risk: patch.risk, state: patch.state, loadPct: patch.loadPct, tempC: patch.tempC }
          : row
      })
    : rows

  const columns: Array<Column<AssetRow>> = [
    {
      key: 'code',
      header: t('assets.columns.code'),
      sortValue: (row) => row.code,
      cell: (row) => (
        <Link
          href={`/assets/${encodeURIComponent(row.code)}`}
          className="font-mono text-xs font-medium text-brand hover:underline"
        >
          {row.code}
        </Link>
      ),
    },
    {
      key: 'name',
      header: t('assets.columns.name'),
      sortValue: (row) => (locale === 'ar' ? row.nameAr : row.name),
      cell: (row) => (
        <span className="block max-w-72 truncate text-text">
          {locale === 'ar' ? row.nameAr : row.name}
        </span>
      ),
    },
    {
      key: 'type',
      header: t('assets.columns.type'),
      secondary: true,
      sortValue: (row) => row.typeKey,
      cell: (row) => <span className="text-text-muted">{t(`assetType.${row.typeKey}`)}</span>,
    },
    {
      key: 'region',
      header: t('assets.columns.region'),
      secondary: true,
      sortValue: (row) => row.regionCode,
      cell: (row) => (
        <span className="text-text-muted">
          {locale === 'ar' ? row.regionNameAr : row.regionName}
        </span>
      ),
    },
    {
      key: 'capacity',
      header: t('assets.columns.capacity'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.capacityMw,
      cell: (row) => (
        <span className="tnum text-text-muted">
          {mw(row.capacityMw)} <span className="text-[10px]">{t('common.units.mw')}</span>
        </span>
      ),
    },
    {
      key: 'load',
      header: t('assets.columns.load'),
      align: 'end',
      sortValue: (row) => row.loadPct,
      cell: (row) => (
        <span className={`tnum ${row.loadPct >= 90 ? 'text-warning' : 'text-text'}`}>
          {n(row.loadPct, { maximumFractionDigits: 0 })}%
        </span>
      ),
    },
    {
      key: 'temperature',
      header: t('assets.columns.temperature'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.tempC,
      cell: (row) => (
        <span
          className={`tnum ${row.tempC >= row.ratedTempC ? 'text-critical' : row.tempC >= row.ratedTempC - 15 ? 'text-warning' : 'text-text-muted'}`}
        >
          {n(row.tempC, { maximumFractionDigits: 0 })}
          {t('common.units.celsius')}
        </span>
      ),
    },
    {
      key: 'health',
      header: t('assets.columns.health'),
      align: 'end',
      sortValue: (row) => row.health,
      cell: (row) => (
        <span className={`tnum font-medium ${styleForHealth(row.health).text}`}>
          {n(row.health, { maximumFractionDigits: 0 })}
        </span>
      ),
    },
    {
      key: 'risk',
      header: t('assets.columns.risk'),
      align: 'end',
      sortValue: (row) => row.risk,
      cell: (row) => (
        <div className="flex items-center justify-end gap-2">
          <Meter value={row.risk} state={row.state} className="hidden w-14 lg:block" />
          <span className={`tnum w-10 text-end font-medium ${styleForRisk(row.risk).text}`}>
            {n(row.risk, { maximumFractionDigits: 0 })}%
          </span>
        </div>
      ),
    },
    {
      key: 'state',
      header: t('assets.columns.status'),
      align: 'end',
      sortValue: (row) => row.risk,
      cell: (row) => (
        <StateBadge
          state={row.state}
          label={t(`states.${row.state}`)}
          size="sm"
          pulse={row.risk >= 75}
        />
      ),
    },
  ]

  return (
    <DataTable
      rows={live}
      columns={columns}
      getRowKey={(row) => row.code}
      searchable={(row) => `${row.code} ${row.name} ${row.nameAr} ${row.regionName} ${row.regionNameAr}`}
      searchPlaceholder={t('common.searchPlaceholder')}
      initialSort={{ key: 'risk', direction: 'desc' }}
      pageSize={25}
      caption={t('assets.title')}
      filters={[
        {
          key: 'type',
          label: t('assets.columns.type'),
          options: ASSET_TYPE_KEYS.map((key) => ({ value: key, label: t(`assetType.${key}`) })),
          match: (row, value) => row.typeKey === value,
        },
        {
          key: 'state',
          label: t('map.filterState'),
          options: GRID_STATES.map((state) => ({ value: state, label: t(`states.${state}`) })),
          match: (row, value) => row.state === value,
        },
        {
          key: 'criticality',
          label: t('assets.columns.criticality'),
          options: CRITICALITIES.map((value) => ({ value, label: t(`severity.${value}`) })),
          match: (row, value) => row.criticality === value,
        },
      ]}
    />
  )
}
