import React, { useState, useEffect } from 'react'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from './ui/dialog'; import { Button } from './ui/button'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select'; import { Label } from './ui/label'; import { AlertCircle, Shield } from 'lucide-react'; import api from '../utils/api'; import { toast } from 'sonner'; export default function ChangeRoleDialog({ open, onClose, user, onSuccess }) { const [roles, setRoles] = useState([]); const [selectedRole, setSelectedRole] = useState(''); const [selectedRoleId, setSelectedRoleId] = useState(null); const [loadingRoles, setLoadingRoles] = useState(false); const [submitting, setSubmitting] = useState(false); useEffect(() => { if (open) { fetchRoles(); // Pre-select current role setSelectedRole(user.role); setSelectedRoleId(user.role_id); } }, [open, user]); const fetchRoles = async () => { setLoadingRoles(true); try { // Reuse existing endpoint that returns assignable roles based on privilege const response = await api.get('/admin/roles/assignable'); // Map API response to format expected by Select component const mappedRoles = response.data.map(role => ({ value: role.code, label: role.name, id: role.id, description: role.description })); setRoles(mappedRoles); } catch (error) { console.error('Failed to fetch assignable roles:', error); toast.error('Failed to load roles. Please try again.'); } finally { setLoadingRoles(false); } }; const handleSubmit = async () => { if (!selectedRole) { toast.error('Please select a role'); return; } // Don't submit if role hasn't changed if (selectedRole === user.role && selectedRoleId === user.role_id) { toast.info('The selected role is the same as current role'); return; } setSubmitting(true); try { await api.put(`/admin/users/${user.id}/role`, { role: selectedRole, role_id: selectedRoleId }); toast.success(`Role changed to ${selectedRole}`); onSuccess(); onClose(); } catch (error) { const message = error.response?.data?.detail || 'Failed to change role'; toast.error(message); } finally { setSubmitting(false); } }; return ( Change User Role Change role for {user.first_name} {user.last_name} ({user.email})
{/* Current Role Display */}

Current Role

{user.role}

{/* Role Selection */}
{/* Warning for privileged roles */} {(selectedRole === 'admin' || selectedRole === 'superadmin') && (

Admin Access Warning

This user will gain full administrative access to the system.

)}
); }