import { useMemo, useState } from 'react'
import { Bot, ArrowUpDown } from 'lucide-react'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { formatCurrency, formatPercent } from '@/lib/format'
import type { ActivitySimResult } from '@/domain/types'

interface ComparisonRow {
  activityId: string
  activityName: string
  actualCost: number
  automatedCost: number
  savings: number
  savingsPercent: number
  automatable: boolean
}

interface ComparisonTableProps {
  perActivityActual: ActivitySimResult[]
  perActivityAutomated: ActivitySimResult[]
  automatableIds: Set<string>   // bpmnElementIds marcados como automatizables
  currency: string
}

export function ComparisonTable({
  perActivityActual,
  perActivityAutomated,
  automatableIds,
  currency,
}: ComparisonTableProps) {
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc')

  const automatedByActivityId = useMemo(() => {
    const m = new Map<string, ActivitySimResult>()
    for (const a of perActivityAutomated) m.set(a.activityId, a)
    return m
  }, [perActivityAutomated])

  const rows: ComparisonRow[] = useMemo(() => {
    return perActivityActual
      .map((act) => {
        const automated = automatedByActivityId.get(act.activityId)
        const automatedCost = automated?.expectedTotalCost ?? act.expectedTotalCost
        const savings = act.expectedTotalCost - automatedCost
        const savingsPercent =
          act.expectedTotalCost > 0 ? (savings / act.expectedTotalCost) * 100 : 0
        return {
          activityId: act.activityId,
          activityName: act.activityName,
          actualCost: act.expectedTotalCost,
          automatedCost,
          savings,
          savingsPercent,
          automatable: automatableIds.has(act.bpmnElementId),
        }
      })
      .sort((a, b) => (b.savings - a.savings) * (sortDir === 'desc' ? 1 : -1))
  }, [perActivityActual, automatedByActivityId, automatableIds, sortDir])

  if (rows.length === 0) {
    return (
      <div className="flex items-center justify-center h-24 text-xs text-slate-400 rounded-xl border border-slate-200">
        Sin actividades para comparar
      </div>
    )
  }

  return (
    <div className="rounded-xl border border-inq-orange/20 overflow-hidden">
      <Table>
        <TableHeader style={{ background: '#FFF8ED', borderBottom: '1px solid #F59845' }}>
          <tr>
            <TableHead className="w-8 text-xs text-amber-800/70" />
            <TableHead className="text-xs text-amber-800/70 font-medium uppercase tracking-wide">Actividad</TableHead>
            <TableHead className="text-xs text-right text-amber-800/70 font-medium uppercase tracking-wide">Costo actual</TableHead>
            <TableHead className="text-xs text-right text-amber-800/70 font-medium uppercase tracking-wide">Costo automatizado</TableHead>
            <TableHead
              className="text-xs text-right cursor-pointer select-none text-amber-800/70 font-medium uppercase tracking-wide hover:text-amber-900"
              onClick={() => setSortDir((d) => (d === 'desc' ? 'asc' : 'desc'))}
            >
              <span className="inline-flex items-center justify-end gap-1">
                Ahorro
                <ArrowUpDown className="h-3 w-3 opacity-40" />
              </span>
            </TableHead>
            <TableHead className="text-xs text-right text-amber-800/70 font-medium uppercase tracking-wide">% ahorro</TableHead>
          </tr>
        </TableHeader>
        <TableBody>
          {rows.map((row) => {
            const savingsColor =
              row.savings > 0
                ? 'text-emerald-700'
                : row.savings < 0
                ? 'text-red-600'
                : 'text-slate-400'
            const rowClass = row.automatable ? '' : 'bg-slate-50/60'
            const textClass = row.automatable ? 'text-slate-800' : 'text-slate-500'
            return (
              <TableRow key={row.activityId} className={rowClass}>
                <TableCell className="py-2">
                  {row.automatable && (
                    <Bot
                      className="h-3.5 w-3.5 text-amber-500"
                      aria-label="Marcada como automatizable"
                    />
                  )}
                </TableCell>
                <TableCell className={`text-xs font-medium max-w-48 truncate ${textClass}`}>
                  {row.activityName}
                </TableCell>
                <TableCell className={`text-xs font-mono text-right ${row.automatable ? 'text-slate-600' : 'text-slate-400'}`}>
                  {formatCurrency(row.actualCost, currency)}
                </TableCell>
                <TableCell className={`text-xs font-mono text-right ${row.automatable ? 'text-slate-600' : 'text-slate-400'}`}>
                  {formatCurrency(row.automatedCost, currency)}
                </TableCell>
                <TableCell className={`text-xs font-mono font-semibold text-right ${row.automatable ? savingsColor : 'text-slate-300'}`}>
                  {row.automatable
                    ? (row.savings > 0 ? '+' : '') + formatCurrency(row.savings, currency)
                    : '—'}
                </TableCell>
                <TableCell className={`text-xs font-mono text-right ${row.automatable ? savingsColor : 'text-slate-300'}`}>
                  {row.automatable
                    ? (row.savings > 0 ? '+' : '') + formatPercent(row.savingsPercent)
                    : '—'}
                </TableCell>
              </TableRow>
            )
          })}
        </TableBody>
      </Table>
    </div>
  )
}
