import React, { useState, useRef } from 'react'; import { SchoolData, User } from '../types'; import { useDialog } from '../DialogContext'; import { Plus, Edit2, Trash2, X, Shield, Lock, User as UserIcon, AlertTriangle, Camera, Loader2 } from 'lucide-react'; import imageCompression from 'browser-image-compression'; import { uploadProfilePicture } from '../services/supabase'; interface UserManagementProps { data: SchoolData; updateData: (newData: Partial) => void; } const UserManagement: React.FC = ({ data, updateData }) => { const { showAlert, showConfirm } = useDialog(); const [isModalOpen, setIsModalOpen] = useState(false); const [isClosing, setIsClosing] = useState(false); const [isUploading, setIsUploading] = useState(false); const [editingUser, setEditingUser] = useState(null); const fileInputRef = useRef(null); const [formData, setFormData] = useState({ name: '', displayName: '', password: '', cpf: '', photoURL: '', role: 'user' as 'admin' | 'user' }); const closeModal = () => { setIsClosing(true); setTimeout(() => { setIsModalOpen(false); setIsClosing(false); setEditingUser(null); setFormData({ name: '', displayName: '', password: '', cpf: '', photoURL: '', role: 'user' }); }, 400); }; const handleEdit = (user: User) => { setEditingUser(user); setFormData({ name: user.name, displayName: user.displayName || '', password: user.password, cpf: user.cpf || '', photoURL: user.photoURL || '', role: user.role || 'user' }); setIsModalOpen(true); }; const handleDelete = (user: User) => { if (data.users.length <= 1) { showAlert('Atenção', '⚠️ Você não pode excluir o último usuário do sistema.', 'warning'); return; } showConfirm( 'Remover Usuário', `Tem certeza que deseja remover o acesso de ${user.name}?`, () => { const updatedUsers = data.users.filter(u => u.id !== user.id); updateData({ users: updatedUsers }); } ); }; const handlePhotoUpload = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; try { setIsUploading(true); // Compression options const options = { maxSizeMB: 0.1, maxWidthOrHeight: 400, useWebWorker: true }; const compressedFile = await imageCompression(file, options); // Upload to Supabase const url = await uploadProfilePicture(editingUser?.id || 'new-user', compressedFile); if (url) { setFormData(prev => ({ ...prev, photoURL: url })); } else { showAlert('Erro', 'Não foi possível fazer o upload da imagem. Verifique a configuração do Supabase.', 'error'); } } catch (error) { console.error('Compression/Upload error:', error); showAlert('Erro', 'Erro ao processar imagem.', 'error'); } finally { setIsUploading(false); } }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); // Basic validation if (formData.name.length < 3) { showAlert('Atenção', '⚠️ O nome deve ter no mínimo 3 caracteres.', 'warning'); return; } if (formData.password.length < 3) { showAlert('Atenção', '⚠️ A senha deve ter no mínimo 3 caracteres.', 'warning'); return; } if (!formData.cpf || formData.cpf.replace(/\D/g, '').length !== 11) { showAlert('Atenção', '⚠️ O CPF é obrigatório e deve ter 11 dígitos.', 'warning'); return; } if (editingUser) { // Check if name is taken by another user const exists = data.users.some(u => (u.name || '').toLowerCase() === (formData.name || '').toLowerCase() && u.id !== editingUser.id); if (exists) { showAlert('Atenção', '⚠️ Este nome de usuário já está em uso.', 'warning'); return; } const updatedUsers = data.users.map(u => u.id === editingUser.id ? { ...u, name: formData.name, displayName: formData.displayName, password: formData.password, cpf: formData.cpf, photoURL: formData.photoURL, role: formData.role } : u ); updateData({ users: updatedUsers }); } else { // Check if name is taken const exists = data.users.some(u => (u.name || '').toLowerCase() === (formData.name || '').toLowerCase()); if (exists) { showAlert('Atenção', '⚠️ Este nome de usuário já está em uso.', 'warning'); return; } const newUser: User = { id: crypto.randomUUID(), name: formData.name, displayName: formData.displayName, password: formData.password, cpf: formData.cpf, photoURL: formData.photoURL, role: formData.role }; updateData({ users: [...data.users, newUser] }); } closeModal(); }; const inputClass = "w-full px-4 py-3 bg-white text-black border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all shadow-sm"; return (

Usuários do Sistema

Gerencie quem tem acesso administrativo ao EduManager.

{data.users.map(user => (
{user.photoURL ? ( {user.name} ) : ( )}

{user.displayName || user.name}

@{user.name} • {user.role === 'admin' ? 'Admin' : 'Usuário'}

))}
{/* CREATE/EDIT MODAL */} {isModalOpen && (
{/* Blue Top Bar */}

{editingUser ? 'Editar Usuário' : 'Novo Usuário'}

Defina as credenciais de acesso.

{/* Photo Upload */}
{formData.photoURL ? ( Preview ) : ( )} {isUploading && (
)}

Foto de Perfil

setFormData({...formData, name: e.target.value})} />
setFormData({...formData, displayName: e.target.value})} />
{ const val = e.target.value.replace(/\D/g, '').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d)/, '$1.$2').replace(/(\d{3})(\d{1,2})/, '$1-$2').slice(0, 14); setFormData({...formData, cpf: val}); }} />
setFormData({...formData, password: e.target.value})} />
)}
); }; export default UserManagement;