'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, StateBadge } from '@/components/ui/display'
import { EVENT_TYPES, PREDICTION_STATUSES, riskToState } from '@/lib/domain/enums'
import { styleForRisk } from '@/lib/ui/state-styles'

export interface PredictionRow {
  id: string
  code: string
  assetCode: string
  assetName: string
  assetNameAr: string
  regionName: string
  regionNameAr: string
  eventType: string
  probability: number
  confidence: number
  severity: string
  riskScore: number
  etaMinutes: number
  etaAt: number
  status: string
  createdAt: number
  dnaCode: string | null
  dnaSimilarity: number
  modelVersion: string
  recommendationCount: number
}

export function PredictionTable({ rows }: { rows: PredictionRow[] }) {
  const { t, locale, n, duration, relative } = useI18n()

  const columns: Array<Column<PredictionRow>> = [
    {
      key: 'code',
      header: t('predictions.columns.code'),
      sortValue: (row) => row.code,
      cell: (row) => (
        <Link
          href={`/predictions/${encodeURIComponent(row.code)}`}
          className="font-mono text-xs font-medium text-brand hover:underline"
        >
          {row.code}
        </Link>
      ),
    },
    {
      key: 'asset',
      header: t('predictions.columns.asset'),
      sortValue: (row) => row.assetCode,
      cell: (row) => (
        <div className="min-w-0">
          <Link
            href={`/assets/${encodeURIComponent(row.assetCode)}`}
            className="font-mono text-xs text-text hover:text-brand"
          >
            {row.assetCode}
          </Link>
          <p className="truncate text-[11px] text-text-faint">
            {locale === 'ar' ? row.regionNameAr : row.regionName}
          </p>
        </div>
      ),
    },
    {
      key: 'event',
      header: t('predictions.columns.event'),
      sortValue: (row) => row.eventType,
      cell: (row) => (
        <div className="min-w-0">
          <span className="text-text">{t(`eventType.${row.eventType}`)}</span>
          {row.dnaCode ? (
            <p className="mt-0.5 font-mono text-[10px] text-text-faint">
              {row.dnaCode} · {n(row.dnaSimilarity, { maximumFractionDigits: 0 })}%
            </p>
          ) : null}
        </div>
      ),
    },
    {
      key: 'probability',
      header: t('predictions.columns.probability'),
      align: 'end',
      sortValue: (row) => row.probability,
      cell: (row) => (
        <span className="tnum">{n(row.probability * 100, { maximumFractionDigits: 0 })}%</span>
      ),
    },
    {
      key: 'confidence',
      header: t('predictions.columns.confidence'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.confidence,
      cell: (row) => (
        <span className="tnum text-text-muted">
          {n(row.confidence * 100, { maximumFractionDigits: 0 })}%
        </span>
      ),
    },
    {
      key: 'eta',
      header: t('predictions.columns.eta'),
      align: 'end',
      sortValue: (row) => row.etaMinutes,
      cell: (row) => <span className="tnum text-text-muted">{duration(row.etaMinutes)}</span>,
    },
    {
      key: 'risk',
      header: t('predictions.columns.risk'),
      align: 'end',
      sortValue: (row) => row.riskScore,
      cell: (row) => (
        <span className={`tnum font-medium ${styleForRisk(row.riskScore).text}`}>
          {n(row.riskScore, { maximumFractionDigits: 0 })}%
        </span>
      ),
    },
    {
      key: 'severity',
      header: t('common.severity'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.riskScore,
      cell: (row) => (
        <StateBadge
          state={riskToState(row.riskScore)}
          label={t(`severity.${row.severity}`)}
          size="sm"
        />
      ),
    },
    {
      key: 'status',
      header: t('predictions.columns.status'),
      align: 'end',
      sortValue: (row) => row.status,
      cell: (row) => (
        <Badge tone={row.status === 'prevented' ? 'brand' : row.status === 'active' ? 'info' : 'muted'}>
          {t(`predictions.status.${row.status}`)}
        </Badge>
      ),
    },
    {
      key: 'created',
      header: t('predictions.columns.created'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.createdAt,
      cell: (row) => <span className="text-[11px] text-text-faint">{relative(row.createdAt)}</span>,
    },
  ]

  return (
    <DataTable
      rows={rows}
      columns={columns}
      getRowKey={(row) => row.id}
      searchable={(row) => `${row.code} ${row.assetCode} ${row.assetName} ${row.assetNameAr}`}
      initialSort={{ key: 'risk', direction: 'desc' }}
      caption={t('predictions.title')}
      emptyTitle={t('predictions.empty')}
      filters={[
        {
          key: 'status',
          label: t('predictions.columns.status'),
          options: PREDICTION_STATUSES.map((status) => ({
            value: status,
            label: t(`predictions.status.${status}`),
          })),
          match: (row, value) => row.status === value,
        },
        {
          key: 'event',
          label: t('predictions.columns.event'),
          options: EVENT_TYPES.map((event) => ({ value: event, label: t(`eventType.${event}`) })),
          match: (row, value) => row.eventType === value,
        },
      ]}
    />
  )
}
