import { Link } from 'react-router-dom'
import { isAxiosError } from 'axios'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { AlertCircle } from 'lucide-react'
import { useRoles } from '../hooks/useRoles'
import { useDeactivateRole } from '../hooks/useDeactivateRole'

export function RolesList() {
  const { data: roles, isLoading, isError, error } = useRoles()
  const deactivateMut = useDeactivateRole()

  if (isLoading) return <p className="text-sm text-muted-foreground">Cargando roles...</p>

  if (isError) {
    const msg = isAxiosError(error) ? (error.message ?? 'Error al cargar roles') : 'Error al cargar roles'
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertDescription>{msg}</AlertDescription>
      </Alert>
    )
  }

  if (!roles || roles.length === 0) {
    return <p className="text-sm text-muted-foreground">No hay roles registrados.</p>
  }

  function handleDeactivate(codigo: string) {
    deactivateMut.mutate(codigo)
  }

  const deactivateErr = deactivateMut.error
  const deactivateErrMsg =
    deactivateErr && isAxiosError(deactivateErr)
      ? (deactivateErr.response?.data as { message?: string } | undefined)?.message ??
        'No se pudo desactivar el rol'
      : deactivateErr
      ? 'No se pudo desactivar el rol'
      : null

  return (
    <div className="space-y-3">
      {deactivateErrMsg && (
        <Alert variant="destructive" role="alert">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>{deactivateErrMsg}</AlertDescription>
        </Alert>
      )}
      <table className="w-full text-sm">
        <thead className="text-left text-muted-foreground">
          <tr>
            <th className="py-2 pr-4">Código</th>
            <th className="py-2 pr-4">Nombre</th>
            <th className="py-2 pr-4">Descripción</th>
            <th className="py-2 pr-4">Estado</th>
            <th className="py-2 pr-4 text-right">Acciones</th>
          </tr>
        </thead>
        <tbody>
          {roles.map((r) => (
            <tr key={r.codigo} className="border-t border-border">
              <td className="py-2 pr-4 font-mono text-xs">{r.codigo}</td>
              <td className="py-2 pr-4">{r.nombre}</td>
              <td className="py-2 pr-4 text-muted-foreground">{r.descripcion ?? '—'}</td>
              <td className="py-2 pr-4">
                {r.activo ? (
                  <Badge>Activo</Badge>
                ) : (
                  <Badge variant="secondary">Inactivo</Badge>
                )}
              </td>
              <td className="py-2 pr-4 text-right space-x-2">
                <Link to={`/admin/roles/${encodeURIComponent(r.codigo)}/editar`}>
                  <Button size="sm" variant="outline">
                    Editar
                  </Button>
                </Link>
                {r.activo && (
                  <Button
                    size="sm"
                    variant="destructive"
                    disabled={deactivateMut.isPending}
                    onClick={() => handleDeactivate(r.codigo)}
                  >
                    Desactivar
                  </Button>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}
