import { useEffect, useMemo, useRef, useState } from 'react'
import { ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { activityColor } from '@/lib/colors'
import { formatCurrency, formatPercent, formatMinutes } from '@/lib/format'
import type { HeatmapMode } from '@/lib/colors'
import type { ActivitySimResult } from '@/domain/types'

type SortKey = 'activityName' | 'expectedDirectCost' | 'expectedIndirectCost' | 'expectedTotalCost' | 'percentOfTotal' | 'executionTimeMinutes' | 'executionProbability'

interface ActivitiesTableProps {
  perActivity: ActivitySimResult[]
  mode: HeatmapMode
  currency: string
  highlightedId: string | null
  onRowClick: (bpmnElementId: string) => void
}

function SortIcon({ column, sortKey, dir }: { column: SortKey; sortKey: SortKey; dir: 'asc' | 'desc' }) {
  if (column !== sortKey) return <ArrowUpDown className="h-3 w-3 ml-1 opacity-40" />
  return dir === 'asc'
    ? <ArrowUp className="h-3 w-3 ml-1 text-primary" />
    : <ArrowDown className="h-3 w-3 ml-1 text-primary" />
}

export function ActivitiesTable({ perActivity, mode, currency, highlightedId, onRowClick }: ActivitiesTableProps) {
  const [sortKey, setSortKey] = useState<SortKey>('expectedTotalCost')
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc')
  const rowRefs = useRef(new Map<string, HTMLTableRowElement>())

  function handleSort(key: SortKey) {
    if (key === sortKey) {
      setSortDir((d) => d === 'asc' ? 'desc' : 'asc')
    } else {
      setSortKey(key)
      setSortDir('desc')
    }
  }

  const sorted = useMemo(() => {
    return [...perActivity].sort((a, b) => {
      const av = a[sortKey]
      const bv = b[sortKey]
      const mult = sortDir === 'asc' ? 1 : -1
      if (typeof av === 'string') return (av as string).localeCompare(bv as string) * mult
      return ((av as number) - (bv as number)) * mult
    })
  }, [perActivity, sortKey, sortDir])

  // Scroll a la fila resaltada
  useEffect(() => {
    if (!highlightedId) return
    const row = rowRefs.current.get(highlightedId)
    if (row) row.scrollIntoView({ behavior: 'smooth', block: 'center' })
  }, [highlightedId])

  function Th({ label, column }: { label: string; column: SortKey }) {
    return (
      <TableHead
        className="cursor-pointer select-none hover:text-foreground whitespace-nowrap"
        onClick={() => handleSort(column)}
      >
        <span className="inline-flex items-center text-xs">
          {label}
          <SortIcon column={column} sortKey={sortKey} dir={sortDir} />
        </span>
      </TableHead>
    )
  }

  return (
    <div className="rounded-xl border border-slate-200 overflow-hidden">
      <Table>
        <TableHeader className="bg-slate-50">
          <tr>
            <TableHead className="w-8 text-xs" />
            <Th label="Actividad" column="activityName" />
            <Th label="Costo directo" column="expectedDirectCost" />
            <Th label="Overhead" column="expectedIndirectCost" />
            <Th label="Costo total" column="expectedTotalCost" />
            <Th label="% total" column="percentOfTotal" />
            <Th label="Tiempo" column="executionTimeMinutes" />
            <Th label="Prob. ejec." column="executionProbability" />
          </tr>
        </TableHeader>
        <TableBody>
          {sorted.map((act) => {
            const color = activityColor(act, perActivity, mode)
            const isHighlighted = act.bpmnElementId === highlightedId

            return (
              <TableRow
                key={act.activityId}
                ref={(el) => { if (el) rowRefs.current.set(act.bpmnElementId, el) }}
                onClick={() => onRowClick(act.bpmnElementId)}
                className={`cursor-pointer ${isHighlighted ? 'bg-primary/5 ring-1 ring-inset ring-primary/20' : ''}`}
                data-state={isHighlighted ? 'selected' : undefined}
              >
                <TableCell className="py-2">
                  <div
                    className="w-3 h-3 rounded-sm flex-shrink-0"
                    style={{ backgroundColor: color }}
                  />
                </TableCell>
                <TableCell className="text-xs font-medium text-slate-800 max-w-48 truncate">
                  {act.activityName}
                </TableCell>
                <TableCell className="text-xs font-mono text-slate-600">
                  {formatCurrency(act.expectedDirectCost, currency)}
                </TableCell>
                <TableCell className="text-xs font-mono text-slate-500">
                  {formatCurrency(act.expectedIndirectCost, currency)}
                </TableCell>
                <TableCell className="text-xs font-mono font-semibold text-slate-800">
                  {formatCurrency(act.expectedTotalCost, currency)}
                </TableCell>
                <TableCell className="text-xs font-mono text-slate-600">
                  {formatPercent(act.percentOfTotal)}
                </TableCell>
                <TableCell className="text-xs font-mono text-slate-500">
                  {act.executionTimeMinutes > 0 ? formatMinutes(act.executionTimeMinutes) : '—'}
                </TableCell>
                <TableCell className="text-xs font-mono text-slate-500">
                  {formatPercent(act.executionProbability * 100)}
                </TableCell>
              </TableRow>
            )
          })}
        </TableBody>
      </Table>
    </div>
  )
}
