import { useState, useEffect } from 'react';
import { getUserRoles, assignRole, revokeRole } from '../services/roleService';
import { Role } from '../types/role';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { useToast } from '@/hooks/useToast';
import { UserPlus, X, Loader2 } from 'lucide-react';
import { AssignRoleDialog } from './AssignRoleDialog';
import { useAuthStore } from '@/stores/auth';

interface UserRolesSectionProps {
  userId: number;
  isAdmin?: boolean;
}

export function UserRolesSection({ userId, isAdmin = false }: UserRolesSectionProps) {
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(true);
  const [assignDialogOpen, setAssignDialogOpen] = useState(false);
  const [selectedRole, setSelectedRole] = useState<Role | null>(null);
  const [revokingId, setRevokingId] = useState<number | null>(null);
  const { toast } = useToast();
  const { user } = useAuthStore();

  // Déterminer si l'utilisateur actuel est admin
  const currentUserIsAdmin = user?.role === 'admin' || user?.role === 'super_admin' || isAdmin;

  useEffect(() => {
    loadRoles();
  }, [userId]);

  const loadRoles = async () => {
    try {
      setLoading(true);
      const data = await getUserRoles(userId);
      setRoles(data);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Erreur lors du chargement des rôles';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleRevoke = async (roleId: number) => {
    try {
      setRevokingId(roleId);
      await revokeRole(userId, roleId);
      toast.success('Rôle révoqué avec succès');
      loadRoles();
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Erreur lors de la révocation';
      toast.error(errorMessage);
    } finally {
      setRevokingId(null);
    }
  };

  const handleAssignClick = () => {
    setAssignDialogOpen(true);
  };

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

  if (loading) {
    return (
      <div className="space-y-4">
        <h3 className="text-lg font-semibold">Rôles</h3>
        <div className="flex items-center gap-2">
          <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
          <span className="text-sm text-muted-foreground">Chargement des rôles...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold">Rôles</h3>
        {currentUserIsAdmin && (
          <Button
            variant="outline"
            size="sm"
            onClick={handleAssignClick}
          >
            <UserPlus className="mr-2 h-4 w-4" />
            Assigner un rôle
          </Button>
        )}
      </div>

      {roles.length === 0 ? (
        <p className="text-sm text-muted-foreground">Aucun rôle assigné</p>
      ) : (
        <div className="flex flex-wrap gap-2">
          {roles.map((role) => (
            <Badge
              key={role.id}
              variant={role.is_system ? 'primary' : 'default'}
              className="flex items-center gap-1"
            >
              <span>{role.display_name}</span>
              {currentUserIsAdmin && (
                <button
                  onClick={() => handleRevoke(role.id)}
                  disabled={revokingId === role.id}
                  className="ml-1 hover:text-red-500 disabled:opacity-50"
                  title="Révoquer le rôle"
                >
                  {revokingId === role.id ? (
                    <Loader2 className="h-3 w-3 animate-spin" />
                  ) : (
                    <X className="h-3 w-3" />
                  )}
                </button>
              )}
            </Badge>
          ))}
        </div>
      )}

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

