import { useState } from 'react';
import { Role } from '../types/role';
import { Table, TableColumn } from '@/components/data/Table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Edit, Trash2, UserPlus, Loader2 } from 'lucide-react';
import { deleteRole, revokeRole } from '../services/roleService';
import { useToast } from '@/hooks/useToast';
import { AssignRoleDialog } from './AssignRoleDialog';
import { Dialog } from '@/components/ui/dialog';

interface RoleListProps {
  roles: Role[];
  onRefresh: () => void;
  onEdit: (role: Role) => void;
}

export function RoleList({ roles, onRefresh, onEdit }: RoleListProps) {
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const [assignDialogOpen, setAssignDialogOpen] = useState(false);
  const [selectedRole, setSelectedRole] = useState<Role | null>(null);
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [roleToDelete, setRoleToDelete] = useState<Role | null>(null);
  const { toast } = useToast();

  const handleDeleteClick = (role: Role) => {
    setRoleToDelete(role);
    setDeleteConfirmOpen(true);
  };

  const handleDeleteConfirm = async () => {
    if (!roleToDelete) return;

    try {
      setDeletingId(roleToDelete.id);
      await deleteRole(roleToDelete.id);
      toast.success('Rôle supprimé avec succès');
      onRefresh();
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Erreur lors de la suppression';
      toast.error(errorMessage);
    } finally {
      setDeletingId(null);
      setDeleteConfirmOpen(false);
      setRoleToDelete(null);
    }
  };

  const handleAssignClick = (role: Role) => {
    setSelectedRole(role);
    setAssignDialogOpen(true);
  };

  const handleAssignSuccess = () => {
    setAssignDialogOpen(false);
    setSelectedRole(null);
    toast.success('Rôle assigné avec succès');
  };

  const columns: TableColumn<Role>[] = [
    {
      key: 'name',
      header: 'Nom',
      render: (role) => (
        <div className="font-medium">{role.name}</div>
      ),
      sortable: true,
    },
    {
      key: 'display_name',
      header: 'Nom d\'affichage',
      render: (role) => role.display_name,
      sortable: true,
    },
    {
      key: 'description',
      header: 'Description',
      render: (role) => (
        <div className="text-sm text-muted-foreground max-w-md truncate">
          {role.description || '-'}
        </div>
      ),
    },
    {
      key: 'is_system',
      header: 'Type',
      render: (role) => (
        role.is_system ? (
          <Badge variant="primary">Système</Badge>
        ) : (
          <Badge variant="default">Personnalisé</Badge>
        )
      ),
    },
    {
      key: 'is_active',
      header: 'Statut',
      render: (role) => (
        role.is_active ? (
          <Badge variant="success">Actif</Badge>
        ) : (
          <Badge variant="error">Inactif</Badge>
        )
      ),
    },
    {
      key: 'permissions',
      header: 'Permissions',
      render: (role) => (
        <span className="text-sm text-muted-foreground">
          {role.permissions?.length || 0} permission(s)
        </span>
      ),
    },
    {
      key: 'actions',
      header: 'Actions',
      render: (role) => (
        <div className="flex gap-2">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => onEdit(role)}
            title="Modifier"
          >
            <Edit className="h-4 w-4" />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            onClick={() => handleAssignClick(role)}
            title="Assigner à un utilisateur"
          >
            <UserPlus className="h-4 w-4" />
          </Button>
          {!role.is_system && (
            <Button
              variant="ghost"
              size="icon"
              onClick={() => handleDeleteClick(role)}
              disabled={deletingId === role.id}
              title="Supprimer"
            >
              {deletingId === role.id ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Trash2 className="h-4 w-4 text-destructive" />
              )}
            </Button>
          )}
        </div>
      ),
    },
  ];

  return (
    <>
      <Table
        columns={columns}
        data={roles}
        getRowId={(role) => role.id.toString()}
        emptyMessage="Aucun rôle trouvé"
      />

      {assignDialogOpen && selectedRole && (
        <AssignRoleDialog
          role={selectedRole}
          open={assignDialogOpen}
          onClose={() => {
            setAssignDialogOpen(false);
            setSelectedRole(null);
          }}
          onSuccess={handleAssignSuccess}
        />
      )}

      <Dialog
        open={deleteConfirmOpen}
        onClose={() => {
          setDeleteConfirmOpen(false);
          setRoleToDelete(null);
        }}
        title="Supprimer le rôle"
        variant="confirm"
        onConfirm={handleDeleteConfirm}
        confirmLabel="Supprimer"
        cancelLabel="Annuler"
      >
        <p>
          Êtes-vous sûr de vouloir supprimer le rôle <strong>{roleToDelete?.display_name}</strong> ?
          Cette action est irréversible.
        </p>
      </Dialog>
    </>
  );
}

