'use client'

import Link from 'next/link'

import { useI18n } from '@/components/providers/i18n-provider'
import { DataTable, type Column } from '@/components/ui/data-table'
import { Badge, Meter } from '@/components/ui/display'
import { CRITICALITIES, healthToBand } from '@/lib/domain/enums'
import { styleForHealth, styleForRisk } from '@/lib/ui/state-styles'

export interface MaintenanceRow {
  code: string
  name: string
  nameAr: string
  typeKey: string
  regionName: string
  regionNameAr: string
  health: number
  failureProbability: number
  rulDays: number
  lastMaintenanceAt: number | null
  nextMaintenanceAt: number | null
  criticality: string
  recommendedKind: string
  priority: string
}

/**
 * The predictive-maintenance worklist (§13).
 *
 * Remaining useful life is the column that changes behaviour: an asset at 60 % health
 * with two years left is a planning item, while the same health with three weeks left is
 * this week's job. Both numbers are shown so the distinction is visible.
 */
export function MaintenanceTable({ rows }: { rows: MaintenanceRow[] }) {
  const { t, locale, n, date } = useI18n()

  const columns: Array<Column<MaintenanceRow>> = [
    {
      key: 'asset',
      header: t('maintenance.columns.asset'),
      sortValue: (row) => row.code,
      cell: (row) => (
        <div className="min-w-0">
          <Link
            href={`/assets/${encodeURIComponent(row.code)}`}
            className="font-mono text-xs font-medium text-brand hover:underline"
          >
            {row.code}
          </Link>
          <p className="truncate text-[11px] text-text-faint">
            {t(`assetType.${row.typeKey}`)} · {locale === 'ar' ? row.regionNameAr : row.regionName}
          </p>
        </div>
      ),
    },
    {
      key: 'health',
      header: t('maintenance.columns.health'),
      align: 'end',
      sortValue: (row) => row.health,
      cell: (row) => (
        <div className="flex items-center justify-end gap-2">
          <Meter value={row.health} className="hidden w-14 lg:block" />
          <span className={`tnum w-8 text-end font-medium ${styleForHealth(row.health).text}`}>
            {n(row.health, { maximumFractionDigits: 0 })}
          </span>
        </div>
      ),
    },
    {
      key: 'band',
      header: t('healthBand.good'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.health,
      cell: (row) => (
        <span className={`text-[11px] ${styleForHealth(row.health).text}`}>
          {t(`healthBand.${healthToBand(row.health)}`)}
        </span>
      ),
    },
    {
      key: 'failure',
      header: t('maintenance.columns.failureProbability'),
      align: 'end',
      sortValue: (row) => row.failureProbability,
      cell: (row) => (
        <span className={`tnum ${styleForRisk(row.failureProbability * 100).text}`}>
          {n(row.failureProbability * 100, { maximumFractionDigits: 0 })}%
        </span>
      ),
    },
    {
      key: 'rul',
      header: t('maintenance.columns.rul'),
      align: 'end',
      sortValue: (row) => row.rulDays,
      cell: (row) => (
        <span
          className={`tnum ${row.rulDays < 30 ? 'text-critical' : row.rulDays < 120 ? 'text-warning' : 'text-text-muted'}`}
        >
          {row.rulDays >= 3650
            ? `> 10 ${t('common.units.years')}`
            : `${n(row.rulDays)} ${t('common.units.days')}`}
        </span>
      ),
    },
    {
      key: 'lastMaintenance',
      header: t('maintenance.columns.lastMaintenance'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.lastMaintenanceAt ?? 0,
      cell: (row) => (
        <span className="text-[11px] text-text-muted">
          {row.lastMaintenanceAt ? date(row.lastMaintenanceAt) : t('common.none')}
        </span>
      ),
    },
    {
      key: 'recommended',
      header: t('maintenance.columns.recommended'),
      secondary: true,
      sortValue: (row) => row.recommendedKind,
      cell: (row) => <Badge tone="muted">{t(`maintenance.kind.${row.recommendedKind}`)}</Badge>,
    },
    {
      key: 'priority',
      header: t('maintenance.columns.priority'),
      align: 'end',
      sortValue: (row) =>
        ({ critical: 4, high: 3, medium: 2, low: 1 })[row.priority as 'critical'] ?? 0,
      cell: (row) => (
        <Badge
          tone={row.priority === 'critical' ? 'neutral' : row.priority === 'high' ? 'info' : 'muted'}
          className={
            row.priority === 'critical'
              ? 'border-critical/40 bg-critical/12 text-critical'
              : undefined
          }
        >
          {t(`severity.${row.priority}`)}
        </Badge>
      ),
    },
  ]

  return (
    <DataTable
      rows={rows}
      columns={columns}
      getRowKey={(row) => row.code}
      searchable={(row) => `${row.code} ${row.name} ${row.nameAr} ${row.regionName}`}
      initialSort={{ key: 'health', direction: 'asc' }}
      caption={t('maintenance.title')}
      emptyTitle={t('maintenance.empty')}
      pageSize={20}
      filters={[
        {
          key: 'priority',
          label: t('maintenance.columns.priority'),
          options: CRITICALITIES.map((value) => ({ value, label: t(`severity.${value}`) })),
          match: (row, value) => row.priority === value,
        },
      ]}
    />
  )
}
