import type { Metadata } from 'next'

import { AssetTable, type AssetRow } from '@/components/console/asset-table'
import { PermissionGate } from '@/components/console/permission-gate'
import { DemoDataBadge, PageHeader, Panel, PanelBody, StatCard } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { getGridSnapshot } from '@/lib/services/grid-service'

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

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

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

  const [snapshot, records] = await Promise.all([
    getGridSnapshot(),
    prisma.asset.findMany({
      select: {
        code: true,
        name: true,
        nameAr: true,
        capacityMw: true,
        ratedTempC: true,
        healthScore: true,
        status: true,
        criticality: true,
        assetType: { select: { key: true } },
        region: { select: { code: true, name: true, nameAr: true } },
      },
    }),
  ])

  const byCode = new Map(snapshot.assets.map((entry) => [entry.profile.code, entry]))

  const rows: AssetRow[] = records.map((record) => {
    const live = byCode.get(record.code)
    return {
      code: record.code,
      name: record.name,
      nameAr: record.nameAr,
      typeKey: record.assetType.key,
      regionCode: record.region.code,
      regionName: record.region.name,
      regionNameAr: record.region.nameAr,
      capacityMw: record.capacityMw,
      loadPct: live?.sample.loadPct ?? 0,
      tempC: live?.sample.tempC ?? 0,
      ratedTempC: record.ratedTempC,
      health: live?.sample.effectiveHealth ?? record.healthScore,
      risk: live?.risk.score ?? 0,
      state: live?.state ?? 'normal',
      status: record.status,
      criticality: record.criticality,
    }
  })

  const atRisk = rows.filter((row) => row.risk >= 55).length
  const degraded = rows.filter((row) => row.health < 60).length
  const totalCapacity = rows.reduce((sum, row) => sum + row.capacityMw, 0)

  return (
    <>
      <PageHeader
        title={t('assets.title')}
        subtitle={t('assets.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('common.assets')} value={formatNumber(locale, rows.length)} />
        <StatCard
          label={t('common.capacity')}
          value={formatNumber(locale, totalCapacity, { maximumFractionDigits: 0 })}
          unit={t('common.units.mw')}
        />
        <StatCard
          label={t('commandCenter.cards.criticalAssets')}
          value={formatNumber(locale, atRisk)}
          state={atRisk > 0 ? 'warning' : 'normal'}
        />
        <StatCard
          label={t('healthBand.poor')}
          value={formatNumber(locale, degraded)}
          state={degraded > 0 ? 'watch' : 'normal'}
          hint={t('maintenance.title')}
        />
      </div>

      <Panel className="mt-6">
        <PanelBody>
          <AssetTable rows={rows} />
        </PanelBody>
      </Panel>
    </>
  )
}
