'use client'

import { useState } from 'react'

import { useI18n } from '@/components/providers/i18n-provider'
import { DataTable, type Column } from '@/components/ui/data-table'
import { Dialog } from '@/components/ui/controls'
import { Badge, KeyValue } from '@/components/ui/display'
import { RiskDelta } from '@/components/charts/risk-gauge'
import { SIMULATION_KINDS } from '@/lib/domain/enums'
import { styleForRisk } from '@/lib/ui/state-styles'

export interface SimulationRow {
  id: string
  code: string
  name: string
  nameAr: string
  kind: string
  status: string
  startedAt: number
  durationMs: number
  appliedActions: string | null
  createdBy: string | null
  riskBefore: number | null
  riskAfter: number | null
  customersImpacted: number | null
  economicImpactSar: number | null
  verdict: string | null
  verdictAr: string | null
}

export function SimulationTable({ rows }: { rows: SimulationRow[] }) {
  const { t, locale, n, dateTime, relative } = useI18n()
  const [detail, setDetail] = useState<SimulationRow | null>(null)

  const columns: Array<Column<SimulationRow>> = [
    {
      key: 'code',
      header: t('simulations.columns.code'),
      sortValue: (row) => row.code,
      cell: (row) => <span className="font-mono text-xs text-brand">{row.code}</span>,
    },
    {
      key: 'name',
      header: t('simulations.columns.name'),
      sortValue: (row) => row.name,
      cell: (row) => (
        <span className="block max-w-72 truncate text-text">
          {locale === 'ar' ? row.nameAr : row.name}
        </span>
      ),
    },
    {
      key: 'kind',
      header: t('simulations.columns.kind'),
      sortValue: (row) => row.kind,
      cell: (row) => <Badge tone="muted">{t(`simulations.kind.${row.kind}`)}</Badge>,
    },
    {
      key: 'riskBefore',
      header: t('simulations.columns.riskBefore'),
      align: 'end',
      sortValue: (row) => row.riskBefore ?? -1,
      cell: (row) =>
        row.riskBefore === null ? (
          <span className="text-text-faint">{t('common.na')}</span>
        ) : (
          <span className={`tnum ${styleForRisk(row.riskBefore).text}`}>
            {n(row.riskBefore, { maximumFractionDigits: 0 })}%
          </span>
        ),
    },
    {
      key: 'riskAfter',
      header: t('simulations.columns.riskAfter'),
      align: 'end',
      sortValue: (row) => row.riskAfter ?? -1,
      cell: (row) =>
        row.riskAfter === null ? (
          <span className="text-text-faint">{t('common.na')}</span>
        ) : (
          <span className={`tnum font-medium ${styleForRisk(row.riskAfter).text}`}>
            {n(row.riskAfter, { maximumFractionDigits: 0 })}%
          </span>
        ),
    },
    {
      key: 'customers',
      header: t('simulations.columns.customers'),
      align: 'end',
      secondary: true,
      sortValue: (row) => row.customersImpacted ?? 0,
      cell: (row) => (
        <span className="tnum text-text-muted">
          {row.customersImpacted ? n(row.customersImpacted) : t('common.na')}
        </span>
      ),
    },
    {
      key: 'by',
      header: t('simulations.columns.by'),
      secondary: true,
      sortValue: (row) => row.createdBy ?? '',
      cell: (row) => <span className="text-text-muted">{row.createdBy ?? t('common.na')}</span>,
    },
    {
      key: 'started',
      header: t('simulations.columns.started'),
      align: 'end',
      sortValue: (row) => row.startedAt,
      cell: (row) => <span className="text-[11px] text-text-faint">{relative(row.startedAt)}</span>,
    },
  ]

  return (
    <>
      <DataTable
        rows={rows}
        columns={columns}
        getRowKey={(row) => row.id}
        searchable={(row) => `${row.code} ${row.name} ${row.nameAr}`}
        initialSort={{ key: 'started', direction: 'desc' }}
        onRowClick={setDetail}
        caption={t('simulations.title')}
        emptyTitle={t('simulations.empty')}
        filters={[
          {
            key: 'kind',
            label: t('simulations.columns.kind'),
            options: SIMULATION_KINDS.map((kind) => ({
              value: kind,
              label: t(`simulations.kind.${kind}`),
            })),
            match: (row, value) => row.kind === value,
          },
        ]}
      />

      <Dialog
        open={detail !== null}
        onClose={() => setDetail(null)}
        title={detail ? (locale === 'ar' ? detail.nameAr : detail.name) : ''}
        description={detail?.code}
        closeLabel={t('common.close')}
      >
        {detail ? (
          <div className="space-y-4">
            {detail.riskBefore !== null && detail.riskAfter !== null ? (
              <RiskDelta
                before={detail.riskBefore}
                after={detail.riskAfter}
                beforeLabel={t('simulations.columns.riskBefore')}
                afterLabel={t('simulations.columns.riskAfter')}
                note={detail.verdict ? (locale === 'ar' ? detail.verdictAr! : detail.verdict) : undefined}
              />
            ) : null}

            <dl className="divide-y divide-border/60">
              <KeyValue label={t('simulations.columns.kind')} value={t(`simulations.kind.${detail.kind}`)} />
              <KeyValue label={t('common.status')} value={detail.status} />
              <KeyValue label={t('simulations.columns.started')} value={dateTime(detail.startedAt)} />
              <KeyValue
                label={t('common.duration.minutes', { value: '' }).trim()}
                value={`${n(detail.durationMs)} ms`}
                mono
              />
              {detail.createdBy ? (
                <KeyValue label={t('simulations.columns.by')} value={detail.createdBy} />
              ) : null}
              {detail.appliedActions ? (
                <KeyValue
                  label={t('recommendations.title')}
                  value={detail.appliedActions
                    .split(',')
                    .map((key) => t(`actionType.${key}`))
                    .join(' · ')}
                />
              ) : null}
              {detail.customersImpacted !== null ? (
                <KeyValue
                  label={t('simulations.results.customersImpacted')}
                  value={n(detail.customersImpacted)}
                  mono
                />
              ) : null}
              {detail.economicImpactSar !== null ? (
                <KeyValue
                  label={t('simulations.results.economicImpact')}
                  value={`${n(detail.economicImpactSar, { maximumFractionDigits: 0 })} ${t('common.units.sar')}`}
                  mono
                />
              ) : null}
            </dl>

            <p className="text-[11px] leading-relaxed text-text-faint">{t('common.simulatedTooltip')}</p>
          </div>
        ) : null}
      </Dialog>
    </>
  )
}
