// T600.4 — TipoDeIvaTable
// Tabla principal para tipos de IVA con acciones por fila
import { useMemo } from 'react'
import type { ColumnDef } from '@tanstack/react-table'
import { Pencil, CalendarPlus, PowerOff, Power } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { DataTable } from '@/components/ui/data-table'
import { HistorialCadenaTooltip } from './HistorialCadenaTooltip'
import { useDeactivateTipoDeIva, useReactivateTipoDeIva } from '../hooks/useTiposDeIva'
import type { TipoDeIva } from '../types/tipoDeIva.types'
import { toast } from 'sonner'

interface TipoDeIvaTableProps {
  rows: TipoDeIva[]
  onEdit: (row: TipoDeIva) => void
  onNuevaVersion: (row: TipoDeIva) => void
  isLoading?: boolean
}

export function TipoDeIvaTable({
  rows,
  onEdit,
  onNuevaVersion,
  isLoading,
}: TipoDeIvaTableProps) {
  const deactivate = useDeactivateTipoDeIva()
  const reactivate = useReactivateTipoDeIva()

  const columns = useMemo<ColumnDef<TipoDeIva>[]>(
    () => [
      {
        accessorKey: 'codigo',
        header: 'Código',
        cell: ({ row }) => (
          <span className="font-mono text-xs font-medium">{row.original.codigo}</span>
        ),
        meta: { priority: 'high' },
      },
      {
        accessorKey: 'descripcion',
        header: 'Descripción',
        meta: { priority: 'high' },
      },
      {
        accessorKey: 'porcentaje',
        header: 'Porcentaje',
        cell: ({ row }) => (
          <span className="tabular-nums">{row.original.porcentaje}%</span>
        ),
        meta: { priority: 'high' },
      },
      {
        id: 'vigencia',
        header: 'Vigencia',
        cell: ({ row }) => {
          const { vigenciaDesde, vigenciaHasta } = row.original
          return (
            <span className="text-sm text-muted-foreground">
              {vigenciaDesde} → {vigenciaHasta ?? <em>abierta</em>}
            </span>
          )
        },
        meta: { priority: 'medium' },
      },
      {
        accessorKey: 'activo',
        header: 'Estado',
        cell: ({ row }) =>
          row.original.activo ? (
            <Badge
              variant="secondary"
              className="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
            >
              Activo
            </Badge>
          ) : (
            <Badge
              variant="secondary"
              className="bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"
            >
              Inactivo
            </Badge>
          ),
        meta: { priority: 'medium' },
      },
      {
        id: 'version',
        header: 'Versión',
        cell: ({ row }) => (
          <div className="flex items-center gap-1">
            <span className="text-xs text-muted-foreground">
              {row.original.predecesorId ? '# en cadena' : 'raíz'}
            </span>
            <HistorialCadenaTooltip id={row.original.id} />
          </div>
        ),
        meta: { priority: 'low' },
      },
      {
        id: 'acciones',
        header: 'Acciones',
        cell: ({ row }) => {
          const item = row.original
          const isPending =
            deactivate.isPending || reactivate.isPending

          return (
            <div
              className="flex items-center gap-1"
              onClick={(e) => e.stopPropagation()}
            >
              <Button
                variant="ghost"
                size="sm"
                aria-label="editar"
                title="Editar"
                className="h-7 w-7 p-0"
                onClick={() => onEdit(item)}
              >
                <Pencil className="h-4 w-4" />
              </Button>

              <Button
                variant="ghost"
                size="sm"
                aria-label="nueva vigencia"
                title="Nueva vigencia"
                className="h-7 w-7 p-0"
                onClick={() => onNuevaVersion(item)}
              >
                <CalendarPlus className="h-4 w-4" />
              </Button>

              {item.activo ? (
                <Button
                  variant="ghost"
                  size="sm"
                  aria-label="desactivar"
                  title="Desactivar"
                  className="h-7 w-7 p-0 text-destructive hover:text-destructive"
                  disabled={isPending}
                  onClick={() => {
                    deactivate.mutate(item.id, {
                      onSuccess: () => toast.success(`${item.codigo} desactivado`),
                      onError: () =>
                        toast.error('Error al desactivar. Intentá de nuevo.'),
                    })
                  }}
                >
                  <PowerOff className="h-4 w-4" />
                </Button>
              ) : (
                <Button
                  variant="ghost"
                  size="sm"
                  aria-label="reactivar"
                  title="Reactivar"
                  className="h-7 w-7 p-0"
                  disabled={isPending}
                  onClick={() => {
                    reactivate.mutate(item.id, {
                      onSuccess: () => toast.success(`${item.codigo} reactivado`),
                      onError: () =>
                        toast.error('Error al reactivar. Intentá de nuevo.'),
                    })
                  }}
                >
                  <Power className="h-4 w-4" />
                </Button>
              )}
            </div>
          )
        },
        meta: { priority: 'high' },
      },
    ],
    [onEdit, onNuevaVersion, deactivate, reactivate],
  )

  return (
    <DataTable
      columns={columns}
      data={rows}
      getRowId={(row) => String(row.id)}
      isLoading={isLoading}
      emptyMessage="Sin resultados — no se encontraron tipos de IVA con los filtros seleccionados."
    />
  )
}
