import type { Metadata } from 'next'

import { MaintenanceTable, type MaintenanceRow } from '@/components/console/maintenance-table'
import { PermissionGate } from '@/components/console/permission-gate'
import {
  Badge,
  DemoDataBadge,
  EmptyState,
  PageHeader,
  Panel,
  PanelBody,
  PanelHeader,
  StatCard,
} from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { prisma } from '@/lib/db'
import { getI18n, localised } from '@/lib/i18n/server'
import { formatDate, formatNumber } from '@/lib/i18n/translate'
import { remainingUsefulLifeDays } from '@/lib/engine/telemetry'
import { getGridSnapshot } from '@/lib/services/grid-service'

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

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

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

  const [snapshot, assets, workOrders] = await Promise.all([
    getGridSnapshot(),
    prisma.asset.findMany({
      select: {
        code: true,
        name: true,
        nameAr: true,
        healthScore: true,
        lastMaintenanceAt: true,
        nextMaintenanceAt: true,
        criticality: true,
        assetType: { select: { key: true } },
        region: { select: { name: true, nameAr: true } },
      },
    }),
    prisma.maintenanceRecord.findMany({
      where: { status: { in: ['scheduled', 'overdue', 'in_progress'] } },
      orderBy: [{ status: 'asc' }, { scheduledAt: 'asc' }],
      take: 40,
      include: { asset: { select: { code: true } } },
    }),
  ])

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

  // Ranking is by consequence, not just condition: a failing unit behind 150 000
  // customers outranks a slightly worse one behind 2 000.
  const rows: MaintenanceRow[] = assets
    .map((asset) => {
      const live = liveByCode.get(asset.code)
      const health = live?.sample.effectiveHealth ?? asset.healthScore
      const risk = live?.risk.score ?? 0
      const rulDays = live ? remainingUsefulLifeDays(live.profile, live.sample) : 9999

      return {
        code: asset.code,
        name: asset.name,
        nameAr: asset.nameAr,
        typeKey: asset.assetType.key,
        regionName: asset.region.name,
        regionNameAr: asset.region.nameAr,
        health,
        failureProbability: Math.min(0.99, risk / 100),
        rulDays,
        lastMaintenanceAt: asset.lastMaintenanceAt?.getTime() ?? null,
        nextMaintenanceAt: asset.nextMaintenanceAt?.getTime() ?? null,
        criticality: asset.criticality,
        recommendedKind:
          health < 55 || rulDays < 30
            ? 'corrective'
            : health < 70 || risk >= 55
              ? 'predictive'
              : 'preventive',
        priority:
          health < 55 || rulDays < 30
            ? 'critical'
            : health < 70 || risk >= 55
              ? 'high'
              : health < 82
                ? 'medium'
                : 'low',
      }
    })
    .sort((a, b) => {
      const score = (row: MaintenanceRow) =>
        (100 - row.health) * 1.6 + row.failureProbability * 100 + Math.max(0, 400 - row.rulDays) / 8
      return score(b) - score(a)
    })

  const criticalCount = rows.filter((row) => row.priority === 'critical').length
  const overdue = workOrders.filter((order) => order.status === 'overdue').length
  const averageRul = rows.length
    ? rows.reduce((sum, row) => sum + Math.min(row.rulDays, 3650), 0) / rows.length
    : 0

  return (
    <>
      <PageHeader
        title={t('maintenance.title')}
        subtitle={t('maintenance.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('severity.critical')}
          value={formatNumber(locale, criticalCount)}
          state={criticalCount > 0 ? 'critical' : 'normal'}
        />
        <StatCard
          label={t('maintenance.status.overdue')}
          value={formatNumber(locale, overdue)}
          state={overdue > 0 ? 'warning' : 'normal'}
        />
        <StatCard
          label={t('maintenance.workOrders')}
          value={formatNumber(locale, workOrders.length)}
        />
        <StatCard
          label={t('maintenance.columns.rul')}
          value={formatNumber(locale, averageRul, { maximumFractionDigits: 0 })}
          unit={t('common.units.days')}
          hint={t('maintenance.rulNote')}
        />
      </div>

      <Panel className="mt-6">
        <PanelHeader title={t('maintenance.title')} subtitle={t('maintenance.rulNote')} />
        <PanelBody>
          <MaintenanceTable rows={rows} />
        </PanelBody>
      </Panel>

      <Panel className="mt-6">
        <PanelHeader
          title={t('maintenance.workOrders')}
          action={<Badge tone="muted">{workOrders.length}</Badge>}
        />
        {workOrders.length === 0 ? (
          <EmptyState title={t('maintenance.empty')} />
        ) : (
          <ul className="divide-y divide-border">
            {workOrders.map((order) => (
              <li key={order.id} className="flex flex-wrap items-center gap-4 px-4 py-3.5 sm:px-5">
                <div className="min-w-0 flex-1">
                  <div className="flex flex-wrap items-center gap-2">
                    <span className="font-mono text-[11px] text-brand">{order.code}</span>
                    <Badge tone="neutral">{t(`maintenance.kind.${order.kind}`)}</Badge>
                    <Badge tone={order.status === 'overdue' ? 'neutral' : 'muted'}>
                      {t(`maintenance.status.${order.status}`)}
                    </Badge>
                    <span className="font-mono text-[11px] text-text-muted">{order.asset.code}</span>
                  </div>
                  <p className="mt-1.5 text-xs leading-relaxed text-text-muted">
                    {localised(order, 'actions', locale)}
                  </p>
                </div>
                <div className="text-end">
                  <p className="text-[10px] uppercase tracking-wide text-text-faint">
                    {t('maintenance.columns.scheduled')}
                  </p>
                  <p
                    className={`text-xs font-medium ${order.status === 'overdue' ? 'text-critical' : 'text-text'}`}
                  >
                    {formatDate(locale, order.scheduledAt)}
                  </p>
                </div>
              </li>
            ))}
          </ul>
        )}
      </Panel>
    </>
  )
}
