import { useEffect, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useRoles } from '@/hooks/useRoles';
import { useUsers } from '@/hooks/useUsers';
import { UserAccountDTO } from '@/types/backend';
import { useToast } from '@/hooks/use-toast';

interface AssignRolesModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  user: UserAccountDTO | null;
  onSuccess: () => void;
}

export function AssignRolesModal({ open, onOpenChange, user, onSuccess }: AssignRolesModalProps) {
  const [selectedRoleIds, setSelectedRoleIds] = useState<string[]>([]);
  const { roles, loading: rolesLoading } = useRoles({ autoFetch: true });
  const { assignRoles } = useUsers({ autoFetch: false });
  const { toast } = useToast();

  useEffect(() => {
    if (user && open) {
      setSelectedRoleIds(user.roleIds || []);
    }
  }, [user, open]);

  const handleToggleRole = (roleId: string) => {
    setSelectedRoleIds((prev) =>
      prev.includes(roleId)
        ? prev.filter((id) => id !== roleId)
        : [...prev, roleId]
    );
  };

  const handleSubmit = async () => {
    if (!user) return;

    try {
      await assignRoles(user.id, selectedRoleIds);
      toast({
        title: 'Sucesso',
        description: 'Perfis atribuídos com sucesso',
      });
      onSuccess();
    } catch (err: any) {
      toast({
        title: 'Erro',
        description: err.message || 'Erro ao atribuir perfis',
        variant: 'destructive',
      });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Atribuir Perfis</DialogTitle>
          <DialogDescription>
            Selecione os perfis para o utilizador <strong>{user?.username}</strong>
          </DialogDescription>
        </DialogHeader>

        <ScrollArea className="max-h-[400px] pr-4">
          <div className="space-y-3">
            {rolesLoading ? (
              <div className="text-center py-4 text-muted-foreground">
                A carregar perfis...
              </div>
            ) : roles.length === 0 ? (
              <div className="text-center py-4 text-muted-foreground">
                Nenhum perfil disponível
              </div>
            ) : (
              roles.map((role) => (
                <div
                  key={role.id}
                  className="flex items-start space-x-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors"
                >
                  <Checkbox
                    id={role.id}
                    checked={selectedRoleIds.includes(role.id)}
                    onCheckedChange={() => handleToggleRole(role.id)}
                  />
                  <Label
                    htmlFor={role.id}
                    className="flex-1 cursor-pointer"
                  >
                    <div className="font-medium">{role.name}</div>
                    {role.description && (
                      <div className="text-sm text-muted-foreground">
                        {role.description}
                      </div>
                    )}
                    <div className="text-xs text-muted-foreground mt-1">
                      Código: {role.code}
                    </div>
                  </Label>
                </div>
              ))
            )}
          </div>
        </ScrollArea>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancelar
          </Button>
          <Button onClick={handleSubmit} disabled={rolesLoading}>
            Guardar
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

