import { useState, useEffect } from 'react'; import { useAuth } from '../context/AuthContext'; import { useNavigate } from 'react-router-dom'; import { useToast } from '../context/ToastContext'; export default function Profile() { const { user, authFetch } = useAuth(); const navigate = useNavigate(); const { showToast } = useToast(); const [formData, setFormData] = useState({ name: '', phone: '' }); const [pwData, setPwData] = useState({ currentPw: '', newPw: '', confirmPw: '' }); const [showPwSection, setShowPwSection] = useState(false); const [showNewPw, setShowNewPw] = useState(false); const [loading, setLoading] = useState(false); useEffect(() => { if (user) { setFormData({ name: user.name || '', phone: user.phone || '' }); } }, [user]); const handleSave = async () => { setLoading(true); try { const payload = { ...formData }; if (showPwSection && pwData.newPw) { if (pwData.newPw !== pwData.confirmPw) { showToast("New passwords do not match", "error"); setLoading(false); return; } payload.current_password = pwData.currentPw; payload.new_password = pwData.newPw; } const res = await authFetch("/api/auth/me", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }); if (!res.ok) { const data = await res.json(); let errorMsg = "Failed to update profile"; if (data.detail) { if (typeof data.detail === 'string') { errorMsg = data.detail; } else if (Array.isArray(data.detail)) { errorMsg = data.detail.map(err => err.msg).join(", "); } else { errorMsg = JSON.stringify(data.detail); } } throw new Error(errorMsg); } showToast("Profile updated successfully. Please log in again if you changed your password.", "success"); if (payload.new_password) { window.location.href = '/login'; } } catch (err) { showToast(err.message, "error"); } finally { setLoading(false); } }; const isAdmin = user?.role === 'admin' || user?.role === 'super_admin'; return (
{user?.email}
Update your account password or review login credentials