// UsersView - Gestione utenti per admin

function UsersView() {
    const { user: currentUser, isAdmin } = useAuth();
    const toast = useToast();
    const [users, setUsers] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [showAddModal, setShowAddModal] = React.useState(false);
    const [editingUser, setEditingUser] = React.useState(null);
    const [confirmModal, setConfirmModal] = React.useState(null); // { type, user }

    const loadData = async () => {
        setLoading(true);
        // Clear existing data first
        setUsers([]);
        
        // Small delay to ensure backend has committed changes
        await new Promise(resolve => setTimeout(resolve, 100));
        
        try {
            // Include inactive users in the list
            const usersData = await ApiUtils.fetchUsers(true);
            // Filter out the current admin user - they shouldn't see themselves in this list
            const filteredUsers = usersData.filter(u => u.id !== currentUser.id);
            // Force new array reference for React to detect changes
            setUsers(filteredUsers.map(u => ({ ...u, _key: Date.now() })));
        } catch (err) {
            toast('Errore nel caricamento utenti: ' + err.message, 'error');
        } finally {
            setLoading(false);
        }
    };

    React.useEffect(() => {
        if (isAdmin) {
            loadData();
        }
    }, [isAdmin]);

    const getRoleBadge = (role) => {
        const styles = {
            admin: 'bg-red-100 text-red-700',
            user: 'bg-blue-100 text-blue-700',
        };
        const labels = {
            admin: 'Admin',
            user: 'Utente',
        };
        return (
            <span className={`px-2 py-1 text-xs font-medium rounded-full ${styles[role] || 'bg-gray-100 text-gray-700'}`}>
                {labels[role] || role}
            </span>
        );
    };

    const handleDeactivate = (user) => {
        if (user.id === currentUser.id) {
            toast('Non puoi disattivare il tuo account', 'error');
            return;
        }
        setConfirmModal({ type: 'deactivate', user });
    };

    const handleReactivate = (user) => {
        setConfirmModal({ type: 'reactivate', user });
    };

    const executeUserAction = async () => {
        if (!confirmModal) return;
        
        const { type, user } = confirmModal;
        setConfirmModal({ ...confirmModal, loading: true });
        
        try {
            if (type === 'deactivate') {
                await ApiUtils.deleteUser(user.id);
                toast('Utente disattivato con successo', 'success');
            } else if (type === 'reactivate') {
                await ApiUtils.updateUser(user.id, { is_active: true });
                toast('Utente riattivato con successo', 'success');
            }
            setConfirmModal(null);
            loadData();
        } catch (err) {
            const errorMsg = type === 'deactivate' 
                ? 'Errore nella disattivazione: ' 
                : 'Errore nella riattivazione: ';
            toast(errorMsg + err.message, 'error');
            setConfirmModal(null);
        }
    };

    if (!isAdmin) {
        return (
            <div className="p-8 text-center">
                <div className="text-slate-400 text-lg">
                    Non hai i permessi per visualizzare questa pagina.
                </div>
            </div>
        );
    }

    return (
        <div className="p-6 space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h2 className="text-2xl font-bold text-slate-800">Gestione Utenti</h2>
                    <p className="text-slate-500 mt-1">Gestisci tutti gli utenti del sistema</p>
                </div>
                <button
                    onClick={() => setShowAddModal(true)}
                    className="flex items-center gap-2 px-4 py-2 bg-brand-500 hover:bg-brand-600 text-white font-medium rounded-lg transition-colors"
                >
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                    </svg>
                    Aggiungi Utente
                </button>
            </div>

            {/* Users Table */}
            <div className="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
                {loading ? (
                    <div className="p-12 text-center">
                        <Spinner size="lg" />
                        <p className="text-slate-500 mt-4">Caricamento utenti...</p>
                    </div>
                ) : users.length === 0 ? (
                    <div className="p-12 text-center">
                        <svg className="w-16 h-16 text-slate-300 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                        </svg>
                        <p className="text-slate-500">Nessun utente trovato</p>
                    </div>
                ) : (
                    <table className="w-full">
                        <thead className="bg-slate-50 border-b border-slate-200">
                            <tr>
                                <th className="px-6 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Utente</th>
                                <th className="px-6 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Ruolo</th>
                                <th className="px-6 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Stato</th>
                                <th className="px-6 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Ultimo Accesso</th>
                                <th className="px-6 py-3 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">Azioni</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-slate-100">
                            {users.map(user => (
                                <tr key={user.id} className="hover:bg-slate-50 transition-colors">
                                    <td className="px-6 py-4">
                                        <div className="flex items-center gap-3">
                                            {user.avatar_path ? (
                                                <img
                                                    src={ApiUsers.getAvatarUrl(user.avatar_path)}
                                                    alt={user.full_name}
                                                    className="w-10 h-10 rounded-full object-cover border border-slate-200"
                                                />
                                            ) : (
                                                <div className="w-10 h-10 bg-gradient-to-br from-brand-400 to-brand-600 rounded-full flex items-center justify-center text-white font-semibold text-sm">
                                                    {user.full_name.charAt(0).toUpperCase()}
                                                </div>
                                            )}
                                            <div>
                                                <div className="font-medium text-slate-800">{user.full_name}</div>
                                                <div className="text-sm text-slate-500">{user.email}</div>
                                            </div>
                                        </div>
                                    </td>
                                    <td className="px-6 py-4">
                                        {getRoleBadge(user.role)}
                                    </td>
                                    <td className="px-6 py-4">
                                        {user.is_active ? (
                                            <span className="inline-flex items-center gap-1 px-2 py-1 bg-green-100 text-green-700 text-xs font-medium rounded-full">
                                                <span className="w-1.5 h-1.5 bg-green-500 rounded-full"></span>
                                                Attivo
                                            </span>
                                        ) : (
                                            <span className="inline-flex items-center gap-1 px-2 py-1 bg-slate-100 text-slate-600 text-xs font-medium rounded-full">
                                                <span className="w-1.5 h-1.5 bg-slate-400 rounded-full"></span>
                                                Inattivo
                                            </span>
                                        )}
                                    </td>
                                    <td className="px-6 py-4 text-sm text-slate-500">
                                        {user.last_login_at 
                                            ? new Date(user.last_login_at).toLocaleDateString('it-IT', { 
                                                day: '2-digit', 
                                                month: 'short', 
                                                year: 'numeric',
                                                hour: '2-digit',
                                                minute: '2-digit'
                                            })
                                            : 'Mai'
                                        }
                                    </td>
                                    <td className="px-6 py-4 text-right">
                                        <div className="flex items-center justify-end gap-2">
                                            <button
                                                onClick={() => setEditingUser(user)}
                                                className="p-2 text-slate-400 hover:text-brand-500 hover:bg-brand-50 rounded-lg transition-colors"
                                                title="Modifica utente"
                                            >
                                                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                                </svg>
                                            </button>
                                            {user.id !== currentUser.id && user.is_active && (
                                                <button
                                                    onClick={() => handleDeactivate(user)}
                                                    className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                                                    title="Disattiva utente"
                                                >
                                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                                                    </svg>
                                                </button>
                                            )}
                                            {user.id !== currentUser.id && !user.is_active && (
                                                <button
                                                    onClick={() => handleReactivate(user)}
                                                    className="p-2 text-slate-400 hover:text-green-500 hover:bg-green-50 rounded-lg transition-colors"
                                                    title="Riattiva utente"
                                                >
                                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                    </svg>
                                                </button>
                                            )}
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                )}
            </div>

            {/* Add User Modal */}
            {showAddModal && (
                <AddUserModal
                    onClose={() => setShowAddModal(false)}
                    onSuccess={() => {
                        setShowAddModal(false);
                        loadData();
                        toast('Utente creato con successo', 'success');
                    }}
                />
            )}

            {/* Edit User Modal */}
            {editingUser && (
                <EditUserModal
                    user={editingUser}
                    currentUserId={currentUser.id}
                    onClose={() => setEditingUser(null)}
                    onSuccess={() => {
                        setEditingUser(null);
                        loadData();
                        toast('Utente aggiornato con successo', 'success');
                    }}
                />
            )}

            {/* Confirmation Modal */}
            {confirmModal && (
                <ConfirmationModal
                    title={confirmModal.type === 'deactivate' ? 'Disattiva Utente' : 'Riattiva Utente'}
                    message={confirmModal.type === 'deactivate' 
                        ? `Sei sicuro di voler disattivare ${confirmModal.user?.full_name}?`
                        : `Sei sicuro di voler riattivare ${confirmModal.user?.full_name}?`
                    }
                    confirmText={confirmModal.type === 'deactivate' ? 'Disattiva' : 'Riattiva'}
                    variant={confirmModal.type === 'deactivate' ? 'warning' : 'info'}
                    loading={confirmModal.loading}
                    onConfirm={executeUserAction}
                    onCancel={() => setConfirmModal(null)}
                />
            )}
        </div>
    );
}

// Add User Modal Component
function AddUserModal({ onClose, onSuccess }) {
    const [formData, setFormData] = React.useState({
        email: '',
        password: '',
        full_name: '',
        role: 'user',
        // Referenti CRUD permissions
        can_create_referenti: false,
        can_read_referenti: false,
        can_update_referenti: false,
        can_delete_referenti: false,
        // Projects CRUD permissions
        can_create_projects: false,
        can_read_projects: false,
        can_update_projects: false,
        can_delete_projects: false,
    });
    const [avatarFile, setAvatarFile] = React.useState(null);
    const [avatarPreview, setAvatarPreview] = React.useState(null);
    const [loading, setLoading] = React.useState(false);
    const [error, setError] = React.useState('');
    const [showPassword, setShowPassword] = React.useState(true);
    const fileInputRef = React.useRef(null);

    const handleAvatarChange = (e) => {
        const file = e.target.files[0];
        if (file) {
            // Validate file type
            const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!allowedTypes.includes(file.type)) {
                setError('Tipo file non supportato. Usa JPG, PNG, GIF o WEBP.');
                return;
            }
            // Validate file size (5MB max)
            if (file.size > 5 * 1024 * 1024) {
                setError('File troppo grande. Massimo 5MB.');
                return;
            }
            setAvatarFile(file);
            setAvatarPreview(URL.createObjectURL(file));
            setError('');
        }
    };

    const handleRemoveAvatar = () => {
        setAvatarFile(null);
        if (avatarPreview) {
            URL.revokeObjectURL(avatarPreview);
            setAvatarPreview(null);
        }
        if (fileInputRef.current) {
            fileInputRef.current.value = '';
        }
    };

    // Cleanup preview URL on unmount
    React.useEffect(() => {
        return () => {
            if (avatarPreview) {
                URL.revokeObjectURL(avatarPreview);
            }
        };
    }, [avatarPreview]);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');
        setLoading(true);

        try {
            // Create user first
            const newUser = await ApiUtils.createUser(formData);

            // Upload avatar if selected
            if (avatarFile && newUser.id) {
                try {
                    await ApiUsers.uploadAvatar(newUser.id, avatarFile);
                } catch (avatarErr) {
                    console.warn('Avatar upload failed:', avatarErr.message);
                    // Continue anyway - user was created successfully
                }
            }

            onSuccess();
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-xl shadow-xl max-w-lg w-full max-h-[90vh] overflow-y-auto">
                <div className="flex items-center justify-between p-6 border-b border-slate-200 sticky top-0 bg-white z-10">
                    <h3 className="text-lg font-semibold text-slate-800">Aggiungi Nuovo Utente</h3>
                    <button onClick={onClose} className="text-slate-400 hover:text-slate-600">
                        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>

                <form onSubmit={handleSubmit} className="p-6 space-y-4">
                    {/* Avatar Picker */}
                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-2">Avatar</label>
                        <div className="flex items-center gap-4">
                            <div className="relative">
                                {avatarPreview ? (
                                    <img
                                        src={avatarPreview}
                                        alt="Avatar preview"
                                        className="w-20 h-20 rounded-full object-cover border-2 border-slate-200"
                                    />
                                ) : (
                                    <div className="w-20 h-20 bg-gradient-to-br from-brand-400 to-brand-600 rounded-full flex items-center justify-center text-white font-semibold text-2xl">
                                        {formData.full_name ? formData.full_name.charAt(0).toUpperCase() : '?'}
                                    </div>
                                )}
                                {avatarPreview && (
                                    <button
                                        type="button"
                                        onClick={handleRemoveAvatar}
                                        className="absolute -top-1 -right-1 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 transition-colors"
                                        title="Rimuovi avatar"
                                    >
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                        </svg>
                                    </button>
                                )}
                            </div>
                            <div className="flex-1">
                                <input
                                    ref={fileInputRef}
                                    type="file"
                                    accept="image/jpeg,image/png,image/gif,image/webp"
                                    onChange={handleAvatarChange}
                                    className="hidden"
                                    id="avatar-upload"
                                />
                                <label
                                    htmlFor="avatar-upload"
                                    className="inline-flex items-center gap-2 px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-medium rounded-lg cursor-pointer transition-colors"
                                >
                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                    </svg>
                                    {avatarPreview ? 'Cambia immagine' : 'Carica immagine'}
                                </label>
                                <p className="text-xs text-slate-500 mt-1">JPG, PNG, GIF o WEBP. Max 5MB.</p>
                            </div>
                        </div>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">Nome Completo</label>
                        <input
                            type="text"
                            value={formData.full_name}
                            onChange={(e) => setFormData({ ...formData, full_name: e.target.value })}
                            className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">Email</label>
                        <input
                            type="email"
                            value={formData.email}
                            onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                            className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">Password</label>
                        <div className="relative">
                            <input
                                type={showPassword ? 'text' : 'password'}
                                value={formData.password}
                                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                                className="w-full px-3 py-2 pr-10 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                required
                                minLength={8}
                            />
                            <button
                                type="button"
                                onClick={() => setShowPassword(!showPassword)}
                                className="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-400 hover:text-slate-600"
                            >
                                {showPassword ? (
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                                    </svg>
                                ) : (
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                    </svg>
                                )}
                            </button>
                        </div>
                        <p className="text-xs text-slate-500 mt-1">Minimo 8 caratteri</p>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">Ruolo</label>
                        <select
                            value={formData.role}
                            onChange={(e) => setFormData({ ...formData, role: e.target.value })}
                            className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                        >
                            <option value="user">Utente</option>
                            <option value="admin">Admin</option>
                        </select>
                    </div>

                    {/* Permissions (only for non-admin users) */}
                    {formData.role === 'user' && (
                        <div className="border border-slate-200 rounded-lg p-4 space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-slate-700">Permessi Utente</label>
                                <p className="text-xs text-slate-500 mt-0.5">Seleziona le operazioni che questo utente può eseguire per ogni risorsa</p>
                            </div>
                            
                            <div className="space-y-4">
                                {/* Gestione Referenti */}
                                <div className="rounded-lg border border-slate-200 bg-slate-50/50 overflow-hidden">
                                    <div className="flex items-center gap-3 p-3 bg-teal-50 border-b border-slate-200">
                                        <div className="w-8 h-8 bg-teal-100 rounded-lg flex items-center justify-center">
                                            <svg className="w-4 h-4 text-teal-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
                                            </svg>
                                        </div>
                                        <div className="flex-1">
                                            <span className="text-sm font-semibold text-slate-700">Gestione Referenti</span>
                                            <p className="text-xs text-slate-500">Persone di riferimento esterne associate ai progetti</p>
                                        </div>
                                    </div>
                                    <div className="p-3">
                                        <div className="grid grid-cols-2 gap-2">
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_create_referenti}
                                                    onChange={(e) => setFormData({ ...formData, can_create_referenti: e.target.checked })}
                                                    className="w-4 h-4 text-teal-500 rounded focus:ring-teal-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Crea</span>
                                                    <p className="text-[10px] text-slate-500">Creare nuovi referenti e associarli ai progetti</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_read_referenti}
                                                    onChange={(e) => setFormData({ ...formData, can_read_referenti: e.target.checked })}
                                                    className="w-4 h-4 text-teal-500 rounded focus:ring-teal-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Visualizza</span>
                                                    <p className="text-[10px] text-slate-500">Visualizzare tutti, non solo quelli dei propri progetti</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_update_referenti}
                                                    onChange={(e) => setFormData({ ...formData, can_update_referenti: e.target.checked })}
                                                    className="w-4 h-4 text-teal-500 rounded focus:ring-teal-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Modifica</span>
                                                    <p className="text-[10px] text-slate-500">Modificare dati e gestire associazioni</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_delete_referenti}
                                                    onChange={(e) => setFormData({ ...formData, can_delete_referenti: e.target.checked })}
                                                    className="w-4 h-4 text-teal-500 rounded focus:ring-teal-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Elimina</span>
                                                    <p className="text-[10px] text-slate-500">Eliminare permanentemente dal sistema</p>
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                </div>

                                {/* Gestione Pratiche */}
                                <div className="rounded-lg border border-slate-200 bg-slate-50/50 overflow-hidden">
                                    <div className="flex items-center gap-3 p-3 bg-blue-50 border-b border-slate-200">
                                        <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
                                            <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
                                            </svg>
                                        </div>
                                        <div className="flex-1">
                                            <span className="text-sm font-semibold text-slate-700">Gestione Pratiche</span>
                                            <p className="text-xs text-slate-500">Pratiche (clienti) e relative configurazioni</p>
                                        </div>
                                    </div>
                                    <div className="p-3">
                                        <div className="grid grid-cols-2 gap-2">
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_create_projects}
                                                    onChange={(e) => setFormData({ ...formData, can_create_projects: e.target.checked })}
                                                    className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Crea</span>
                                                    <p className="text-[10px] text-slate-500">Creare nuove pratiche nel sistema</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_read_projects}
                                                    onChange={(e) => setFormData({ ...formData, can_read_projects: e.target.checked })}
                                                    className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Visualizza</span>
                                                    <p className="text-[10px] text-slate-500">Visualizzare tutti, non solo quelli dei propri progetti</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_update_projects}
                                                    onChange={(e) => setFormData({ ...formData, can_update_projects: e.target.checked })}
                                                    className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Modifica</span>
                                                    <p className="text-[10px] text-slate-500">Modificare pratiche e assegnare utenti</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_delete_projects}
                                                    onChange={(e) => setFormData({ ...formData, can_delete_projects: e.target.checked })}
                                                    className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Elimina</span>
                                                    <p className="text-[10px] text-slate-500">Archiviare e ripristinare pratiche</p>
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    {error && (
                        <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">
                            {error}
                        </div>
                    )}

                    <div className="flex gap-3 pt-4">
                        <button
                            type="button"
                            onClick={onClose}
                            className="flex-1 px-4 py-2 border border-slate-200 text-slate-600 font-medium rounded-lg hover:bg-slate-50 transition-colors"
                        >
                            Annulla
                        </button>
                        <button
                            type="submit"
                            disabled={loading}
                            className="flex-1 px-4 py-2 bg-brand-500 text-white font-medium rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-50"
                        >
                            {loading ? 'Creazione...' : 'Crea Utente'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}

// Edit User Modal Component
function EditUserModal({ user, currentUserId, onClose, onSuccess }) {
    const [formData, setFormData] = React.useState({
        email: user.email,
        full_name: user.full_name,
        role: user.role,
        password: '',
        is_active: user.is_active,
        // Referenti CRUD permissions
        can_create_referenti: user.can_create_referenti || false,
        can_read_referenti: user.can_read_referenti || false,
        can_update_referenti: user.can_update_referenti || false,
        can_delete_referenti: user.can_delete_referenti || false,
        // Projects CRUD permissions
        can_create_projects: user.can_create_projects || false,
        can_read_projects: user.can_read_projects || false,
        can_update_projects: user.can_update_projects || false,
        can_delete_projects: user.can_delete_projects || false,
    });
    const [avatarFile, setAvatarFile] = React.useState(null);
    const [avatarPreview, setAvatarPreview] = React.useState(
        user.avatar_path ? ApiUsers.getAvatarUrl(user.avatar_path) : null
    );
    const [avatarDeleted, setAvatarDeleted] = React.useState(false);
    const [loading, setLoading] = React.useState(false);
    const [error, setError] = React.useState('');
    const [showPassword, setShowPassword] = React.useState(true);
    const fileInputRef = React.useRef(null);

    const handleAvatarChange = (e) => {
        const file = e.target.files[0];
        if (file) {
            // Validate file type
            const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!allowedTypes.includes(file.type)) {
                setError('Tipo file non supportato. Usa JPG, PNG, GIF o WEBP.');
                return;
            }
            // Validate file size (5MB max)
            if (file.size > 5 * 1024 * 1024) {
                setError('File troppo grande. Massimo 5MB.');
                return;
            }
            setAvatarFile(file);
            setAvatarPreview(URL.createObjectURL(file));
            setAvatarDeleted(false);
            setError('');
        }
    };

    const handleRemoveAvatar = () => {
        setAvatarFile(null);
        if (avatarPreview && !avatarPreview.startsWith('/api/')) {
            URL.revokeObjectURL(avatarPreview);
        }
        setAvatarPreview(null);
        setAvatarDeleted(true);
        if (fileInputRef.current) {
            fileInputRef.current.value = '';
        }
    };

    // Cleanup preview URL on unmount
    React.useEffect(() => {
        return () => {
            if (avatarPreview && !avatarPreview.startsWith('/api/')) {
                URL.revokeObjectURL(avatarPreview);
            }
        };
    }, [avatarPreview]);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');
        setLoading(true);

        try {
            // Only include fields that have actually changed
            const updateData = {};

            if (formData.email !== user.email) {
                updateData.email = formData.email;
            }
            if (formData.full_name !== user.full_name) {
                updateData.full_name = formData.full_name;
            }
            if (formData.role !== user.role) {
                updateData.role = formData.role;
            }
            // Referenti CRUD permissions
            if (formData.can_create_referenti !== (user.can_create_referenti || false)) {
                updateData.can_create_referenti = formData.can_create_referenti;
            }
            if (formData.can_read_referenti !== (user.can_read_referenti || false)) {
                updateData.can_read_referenti = formData.can_read_referenti;
            }
            if (formData.can_update_referenti !== (user.can_update_referenti || false)) {
                updateData.can_update_referenti = formData.can_update_referenti;
            }
            if (formData.can_delete_referenti !== (user.can_delete_referenti || false)) {
                updateData.can_delete_referenti = formData.can_delete_referenti;
            }
            // Projects CRUD permissions
            if (formData.can_create_projects !== (user.can_create_projects || false)) {
                updateData.can_create_projects = formData.can_create_projects;
            }
            if (formData.can_read_projects !== (user.can_read_projects || false)) {
                updateData.can_read_projects = formData.can_read_projects;
            }
            if (formData.can_update_projects !== (user.can_update_projects || false)) {
                updateData.can_update_projects = formData.can_update_projects;
            }
            if (formData.can_delete_projects !== (user.can_delete_projects || false)) {
                updateData.can_delete_projects = formData.can_delete_projects;
            }
            if (formData.is_active !== user.is_active) {
                updateData.is_active = formData.is_active;
            }
            if (formData.password) {
                updateData.password = formData.password;
            }

            // Update user data if there are changes
            if (Object.keys(updateData).length > 0) {
                await ApiUtils.updateUser(user.id, updateData);
            }

            // Handle avatar changes
            if (avatarFile) {
                // Upload new avatar
                await ApiUsers.uploadAvatar(user.id, avatarFile);
            } else if (avatarDeleted && user.avatar_path) {
                // Delete existing avatar
                await ApiUsers.deleteAvatar(user.id);
            }

            // Check if there's anything changed (including avatar)
            if (Object.keys(updateData).length === 0 && !avatarFile && !avatarDeleted) {
                onClose();
                return;
            }

            onSuccess();
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    const isSelf = user.id === currentUserId;

    return (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-xl shadow-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                <div className="flex items-center justify-between p-6 border-b border-slate-200 sticky top-0 bg-white z-10">
                    <h3 className="text-lg font-semibold text-slate-800">Modifica Utente</h3>
                    <button onClick={onClose} className="text-slate-400 hover:text-slate-600">
                        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>

                <form onSubmit={handleSubmit} className="p-6 space-y-4">
                    {/* Avatar Picker */}
                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-2">Avatar</label>
                        <div className="flex items-center gap-4">
                            <div className="relative">
                                {avatarPreview ? (
                                    <img
                                        src={avatarPreview}
                                        alt="Avatar preview"
                                        className="w-20 h-20 rounded-full object-cover border-2 border-slate-200"
                                    />
                                ) : (
                                    <div className="w-20 h-20 bg-gradient-to-br from-brand-400 to-brand-600 rounded-full flex items-center justify-center text-white font-semibold text-2xl">
                                        {formData.full_name ? formData.full_name.charAt(0).toUpperCase() : '?'}
                                    </div>
                                )}
                                {avatarPreview && (
                                    <button
                                        type="button"
                                        onClick={handleRemoveAvatar}
                                        className="absolute -top-1 -right-1 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600 transition-colors"
                                        title="Rimuovi avatar"
                                    >
                                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                        </svg>
                                    </button>
                                )}
                            </div>
                            <div className="flex-1">
                                <input
                                    ref={fileInputRef}
                                    type="file"
                                    accept="image/jpeg,image/png,image/gif,image/webp"
                                    onChange={handleAvatarChange}
                                    className="hidden"
                                    id="avatar-edit-upload"
                                />
                                <label
                                    htmlFor="avatar-edit-upload"
                                    className="inline-flex items-center gap-2 px-3 py-2 bg-slate-100 hover:bg-slate-200 text-slate-700 text-sm font-medium rounded-lg cursor-pointer transition-colors"
                                >
                                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                                    </svg>
                                    {avatarPreview ? 'Cambia immagine' : 'Carica immagine'}
                                </label>
                                <p className="text-xs text-slate-500 mt-1">JPG, PNG, GIF o WEBP. Max 5MB.</p>
                            </div>
                        </div>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">Nome Completo</label>
                        <input
                            type="text"
                            value={formData.full_name}
                            onChange={(e) => setFormData({ ...formData, full_name: e.target.value })}
                            className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">Email</label>
                        <input
                            type="email"
                            value={formData.email}
                            onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                            className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                            required
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">
                            Nuova Password
                            <span className="text-slate-400 font-normal"> (lascia vuoto per mantenere quella attuale)</span>
                        </label>
                        <div className="relative">
                            <input
                                type={showPassword ? 'text' : 'password'}
                                value={formData.password}
                                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                                className="w-full px-3 py-2 pr-10 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                                minLength={8}
                                placeholder={showPassword ? '' : '••••••••'}
                            />
                            <button
                                type="button"
                                onClick={() => setShowPassword(!showPassword)}
                                className="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-400 hover:text-slate-600"
                            >
                                {showPassword ? (
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                                    </svg>
                                ) : (
                                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                    </svg>
                                )}
                            </button>
                        </div>
                        <p className="text-xs text-slate-500 mt-1">Minimo 8 caratteri se modificata</p>
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">Ruolo</label>
                        <select
                            value={formData.role}
                            onChange={(e) => setFormData({ ...formData, role: e.target.value })}
                            className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
                            disabled={isSelf}
                        >
                            <option value="user">Utente</option>
                            <option value="admin">Admin</option>
                        </select>
                        {isSelf && (
                            <p className="text-xs text-slate-500 mt-1">Non puoi modificare il tuo ruolo</p>
                        )}
                    </div>

                    {/* Permissions (only for non-admin users) */}
                    {formData.role === 'user' && (
                        <div className="border border-slate-200 rounded-lg p-4 space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-slate-700">Permessi Utente</label>
                                <p className="text-xs text-slate-500 mt-0.5">Seleziona le operazioni che questo utente può eseguire per ogni risorsa</p>
                            </div>
                            
                            <div className="space-y-4">
                                {/* Gestione Referenti */}
                                <div className="rounded-lg border border-slate-200 bg-slate-50/50 overflow-hidden">
                                    <div className="flex items-center gap-3 p-3 bg-teal-50 border-b border-slate-200">
                                        <div className="w-8 h-8 bg-teal-100 rounded-lg flex items-center justify-center">
                                            <svg className="w-4 h-4 text-teal-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" />
                                            </svg>
                                        </div>
                                        <div className="flex-1">
                                            <span className="text-sm font-semibold text-slate-700">Gestione Referenti</span>
                                            <p className="text-xs text-slate-500">Persone di riferimento esterne associate ai progetti</p>
                                        </div>
                                    </div>
                                    <div className="p-3">
                                        <div className="grid grid-cols-2 gap-2">
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_create_referenti}
                                                    onChange={(e) => setFormData({ ...formData, can_create_referenti: e.target.checked })}
                                                    className="w-4 h-4 text-teal-500 rounded focus:ring-teal-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Crea</span>
                                                    <p className="text-[10px] text-slate-500">Creare nuovi referenti e associarli ai progetti</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_read_referenti}
                                                    onChange={(e) => setFormData({ ...formData, can_read_referenti: e.target.checked })}
                                                    className="w-4 h-4 text-teal-500 rounded focus:ring-teal-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Visualizza</span>
                                                    <p className="text-[10px] text-slate-500">Visualizzare tutti, non solo quelli dei propri progetti</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_update_referenti}
                                                    onChange={(e) => setFormData({ ...formData, can_update_referenti: e.target.checked })}
                                                    className="w-4 h-4 text-teal-500 rounded focus:ring-teal-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Modifica</span>
                                                    <p className="text-[10px] text-slate-500">Modificare dati e gestire associazioni</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_delete_referenti}
                                                    onChange={(e) => setFormData({ ...formData, can_delete_referenti: e.target.checked })}
                                                    className="w-4 h-4 text-teal-500 rounded focus:ring-teal-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Elimina</span>
                                                    <p className="text-[10px] text-slate-500">Eliminare permanentemente dal sistema</p>
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                </div>

                                {/* Gestione Pratiche */}
                                <div className="rounded-lg border border-slate-200 bg-slate-50/50 overflow-hidden">
                                    <div className="flex items-center gap-3 p-3 bg-blue-50 border-b border-slate-200">
                                        <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
                                            <svg className="w-4 h-4 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
                                            </svg>
                                        </div>
                                        <div className="flex-1">
                                            <span className="text-sm font-semibold text-slate-700">Gestione Pratiche</span>
                                            <p className="text-xs text-slate-500">Pratiche (clienti) e relative configurazioni</p>
                                        </div>
                                    </div>
                                    <div className="p-3">
                                        <div className="grid grid-cols-2 gap-2">
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_create_projects}
                                                    onChange={(e) => setFormData({ ...formData, can_create_projects: e.target.checked })}
                                                    className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Crea</span>
                                                    <p className="text-[10px] text-slate-500">Creare nuove pratiche nel sistema</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_read_projects}
                                                    onChange={(e) => setFormData({ ...formData, can_read_projects: e.target.checked })}
                                                    className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Visualizza</span>
                                                    <p className="text-[10px] text-slate-500">Visualizzare tutti, non solo quelli dei propri progetti</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_update_projects}
                                                    onChange={(e) => setFormData({ ...formData, can_update_projects: e.target.checked })}
                                                    className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Modifica</span>
                                                    <p className="text-[10px] text-slate-500">Modificare pratiche e assegnare utenti</p>
                                                </div>
                                            </label>
                                            <label className="flex items-center gap-2 p-2 rounded-md hover:bg-white cursor-pointer transition-colors">
                                                <input
                                                    type="checkbox"
                                                    checked={formData.can_delete_projects}
                                                    onChange={(e) => setFormData({ ...formData, can_delete_projects: e.target.checked })}
                                                    className="w-4 h-4 text-blue-500 rounded focus:ring-blue-500"
                                                />
                                                <div>
                                                    <span className="text-xs font-medium text-slate-700">Elimina</span>
                                                    <p className="text-[10px] text-slate-500">Archiviare e ripristinare pratiche</p>
                                                </div>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    <div>
                        <label className="flex items-center gap-2 cursor-pointer">
                            <input
                                type="checkbox"
                                checked={formData.is_active}
                                onChange={(e) => setFormData({ ...formData, is_active: e.target.checked })}
                                className="w-4 h-4 text-brand-500 rounded focus:ring-brand-500"
                                disabled={isSelf}
                            />
                            <span className="text-sm font-medium text-slate-700">Attivo</span>
                        </label>
                        {isSelf && (
                            <p className="text-xs text-slate-500 mt-1 ml-6">Non puoi disattivarti</p>
                        )}
                    </div>

                    {error && (
                        <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-sm text-red-600">
                            {error}
                        </div>
                    )}

                    <div className="flex gap-3 pt-4">
                        <button
                            type="button"
                            onClick={onClose}
                            className="flex-1 px-4 py-2 border border-slate-200 text-slate-600 font-medium rounded-lg hover:bg-slate-50 transition-colors"
                        >
                            Annulla
                        </button>
                        <button
                            type="submit"
                            disabled={loading}
                            className="flex-1 px-4 py-2 bg-brand-500 text-white font-medium rounded-lg hover:bg-brand-600 transition-colors disabled:opacity-50"
                        >
                            {loading ? 'Salvataggio...' : 'Salva Modifiche'}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    );
}

window.UsersView = UsersView;
