import { useState, useEffect } from 'react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Dialog, DialogContent, DialogHeader, DialogTitle, } from '@/components/ui/dialog'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; import { UserProfile, UserFunction, UserPrivilege } from '@/hooks/useUserManagement'; import { AvatarUpload } from '@/components/ui/avatar-upload'; import { useProfileImage } from '@/hooks/useProfileImage'; import { usePasswordManagement } from '@/hooks/usePasswordManagement'; import { useUserManagement } from '@/hooks/useUserManagement'; import { Eye, EyeOff, AlertTriangle } from 'lucide-react'; interface UserModalProps { user: UserProfile | null; functions: UserFunction[]; privileges: UserPrivilege[]; onSave?: (userId: string, data: Partial) => void; onCreate?: (data: { email: string; full_name?: string; function_id?: string; privilege_id?: string }) => void; onClose: () => void; readOnly?: boolean; } export function UserModal({ user, functions, privileges, onSave, onCreate, onClose, readOnly = false }: UserModalProps) { const { updateProfileImage, removeProfileImage, updating } = useProfileImage(); const { changeUserPassword, isChangingPassword } = usePasswordManagement(); const { deleteUserAndLogtoAccount } = useUserManagement(); const [showPassword, setShowPassword] = useState(false); const [isDeletingLogto, setIsDeletingLogto] = useState(false); const [formData, setFormData] = useState({ email: '', full_name: '', function_id: '', privilege_id: '', status: 'active' as 'pending' | 'active' | 'inactive' | 'rejected', profile_image_url: null as string | null, password: '' }); const isCreateMode = !user; const isReadOnly = readOnly || (!onSave && !onCreate); useEffect(() => { if (user) { setFormData({ email: user.email || '', full_name: user.full_name || '', function_id: user.function_id || '', privilege_id: user.privilege_id || '', status: user.status, profile_image_url: user.profile_image_url, password: '' // Não mostramos a senha atual por segurança }); } else { // Reset form for create mode setFormData({ email: '', full_name: '', function_id: '', privilege_id: '', status: 'active', profile_image_url: null, password: 'usuario' // Senha padrão para novos usuários }); } }, [user]); const handleImageUpload = async (imageUrl: string) => { if (!user || isReadOnly) return; const success = await updateProfileImage(user.id, imageUrl); if (success) { setFormData(prev => ({ ...prev, profile_image_url: imageUrl })); } }; const handleImageRemove = async () => { if (!user || isReadOnly) return; const success = await removeProfileImage(user.id); if (success) { setFormData(prev => ({ ...prev, profile_image_url: null })); } }; const handlePasswordChange = async () => { if (!user || isReadOnly || !formData.password.trim()) return; await changeUserPassword(user.id, formData.password); }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (isReadOnly) return; if (isCreateMode && onCreate) { // Create new user onCreate({ email: formData.email, full_name: formData.full_name || undefined, function_id: formData.function_id || undefined, privilege_id: formData.privilege_id || undefined }); } else if (user && onSave) { // Update existing user const updateData: Partial = { full_name: formData.full_name, function_id: formData.function_id || null, privilege_id: formData.privilege_id || null, status: formData.status, profile_image_url: formData.profile_image_url }; onSave(user.id, updateData); } onClose(); }; const handleDeleteLogtoAndSupabase = async () => { if (!user || isReadOnly) return; if (confirm(`ATENÇÃO! Esta ação irá apagar a conta do usuário ${user.email} permanentemente no LOGTO e no Supabase. O usuário perderá o acesso totalmente. Tem certeza?`)) { setIsDeletingLogto(true); const success = await deleteUserAndLogtoAccount(user.id, user.email); setIsDeletingLogto(false); if (success) { onClose(); } } }; return ( {isReadOnly ? 'Visualizar Usuário' : isCreateMode ? 'Novo Usuário' : 'Editar Usuário'}
{/* Profile Image Upload - Only for edit mode */} {user && (
)}
setFormData(prev => ({ ...prev, email: e.target.value }))} disabled={!isCreateMode || isReadOnly} className="bg-slate-700 border-slate-600 text-white mt-1" placeholder="Digite o email" required={!isReadOnly} readOnly={isReadOnly} />
{/* Campo de Senha */}
setFormData(prev => ({ ...prev, password: e.target.value }))} className="bg-slate-700 border-slate-600 text-slate-400 pr-10" placeholder={isCreateMode ? "usuario" : "Digite a nova senha"} disabled={isReadOnly} readOnly={isReadOnly} />
{!isCreateMode && !isReadOnly && ( )}
setFormData(prev => ({ ...prev, full_name: e.target.value }))} className="bg-slate-700 border-slate-600 text-white mt-1" placeholder="Digite o nome completo" disabled={isReadOnly} readOnly={isReadOnly} />
{/* Status - Only for edit mode */} {!isCreateMode && (
)} {/* Password info for create mode */} {isCreateMode && !isReadOnly && (

Senha padrão: usuario

O usuário poderá alterar a senha após o primeiro login.

)}
{!isReadOnly && ( )} {!isCreateMode && !isReadOnly && ( )}
); }