import { useEffect, useMemo, useRef, useState } from 'react'
import { ArrowUpDown, ArrowUp, ArrowDown, ChevronRight } 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[]
  pairedBreakdown?: Record<string, Array<{ resourceId: string; resourceName: string; cost: number }>>
  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, pairedBreakdown, mode, currency, highlightedId, onRowClick }: ActivitiesTableProps) {
  const [sortKey, setSortKey] = useState<SortKey>('expectedTotalCost')
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc')
  const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set())
  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')
    }
  }

  function toggleRow(activityId: string) {
    setExpandedRows(prev => {
      const next = new Set(prev)
      if (next.has(activityId)) next.delete(activityId)
      else next.add(activityId)
      return next
    })
  }

  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-10 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
            const isExpanded = expandedRows.has(act.activityId)

            // Costo fijo esperado = total directo − suma de costos de recursos
            const resourceTotal = act.resourceCostBreakdown.reduce((s, r) => s + r.cost, 0)
            const fixedCostExpected = act.expectedDirectCost - resourceTotal

            // Mostrar chevron a menos que no haya absolutamente nada que mostrar
            const hasBreakdown = !(act.resourceCostBreakdown.length === 0 && act.expectedDirectCost === 0)

            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}
                >
                  {/* Chevron + indicador de color en la misma celda */}
                  <TableCell className="py-2 pr-1">
                    <div className="flex items-center gap-1">
                      {hasBreakdown ? (
                        <button
                          onClick={(e) => { e.stopPropagation(); toggleRow(act.activityId) }}
                          className="text-slate-400 hover:text-slate-600 transition-colors flex-shrink-0"
                          aria-label={isExpanded ? 'Colapsar desglose' : 'Expandir desglose'}
                        >
                          <ChevronRight
                            className="h-3.5 w-3.5 transition-transform duration-150"
                            style={{ transform: isExpanded ? 'rotate(90deg)' : 'rotate(0deg)' }}
                          />
                        </button>
                      ) : (
                        <span className="w-3.5" />
                      )}
                      <div
                        className="w-3 h-3 rounded-sm flex-shrink-0"
                        style={{ backgroundColor: color }}
                      />
                    </div>
                  </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>

                {/* Fila expandida con desglose de costos */}
                {isExpanded && (
                  <TableRow key={`${act.activityId}-breakdown`} className="bg-slate-50/70 hover:bg-slate-50/70">
                    <TableCell />
                    <TableCell colSpan={7} className="py-2 pl-4 pr-6">
                      <div className="space-y-1">
                        {pairedBreakdown?.[act.activityId] ? (
                          <>
                            <p className="text-[10px] font-semibold text-slate-400 uppercase tracking-wide mt-1">AS-IS</p>
                            {pairedBreakdown[act.activityId].map((r) => (
                              <div key={r.resourceId} className="flex justify-between text-xs">
                                <span className="text-slate-600">{r.resourceName}</span>
                                <span className="font-mono">{formatCurrency(r.cost, currency)}</span>
                              </div>
                            ))}
                            {pairedBreakdown[act.activityId].length === 0 && (
                              <p className="text-xs text-slate-400 italic">Sin recursos AS-IS</p>
                            )}
                            <p className="text-[10px] font-semibold text-slate-400 uppercase tracking-wide mt-2">TO-BE</p>
                            {act.resourceCostBreakdown.length === 0
                              ? <p className="text-xs text-slate-400 italic">Sin recursos TO-BE</p>
                              : act.resourceCostBreakdown.map((r) => (
                                  <div key={r.resourceId} className="flex justify-between text-xs">
                                    <span className="text-slate-600">{r.resourceName}</span>
                                    <span className="font-mono">{formatCurrency(r.cost, currency)}</span>
                                  </div>
                                ))
                            }
                          </>
                        ) : (
                          <>
                            {fixedCostExpected > 0 && (
                              <div className="flex justify-between text-xs text-slate-500">
                                <span>Fijo (insumos, licencias)</span>
                                <span className="font-mono">{formatCurrency(fixedCostExpected, currency)}</span>
                              </div>
                            )}
                            {act.resourceCostBreakdown.map((r) => (
                              <div key={r.resourceId} className="flex justify-between text-xs text-slate-500">
                                <span>{r.resourceName}</span>
                                <span className="font-mono">{formatCurrency(r.cost, currency)}</span>
                              </div>
                            ))}
                            {act.resourceCostBreakdown.length === 0 && fixedCostExpected === 0 && (
                              <p className="text-xs text-slate-400">Sin desglose disponible</p>
                            )}
                            {act.resourceCostBreakdown.length === 0 && fixedCostExpected > 0 && (
                              <p className="text-xs text-slate-400 mt-0.5">Sin recursos asignados — costo es 100% fijo</p>
                            )}
                          </>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                )}
              </>
            )
          })}
        </TableBody>
      </Table>
    </div>
  )
}
