import React, { useEffect, useState } from 'react'; import Modal from './Modal'; import { authAPI } from '../services/api'; const ChangeMyPasswordModal = ({ open, onClose, onToast }) => { const [currentPw, setCurrentPw] = useState(''); const [newPw, setNewPw] = useState(''); const [confirmPw, setConfirmPw] = useState(''); const [error, setError] = useState(''); const [busy, setBusy] = useState(false); useEffect(() => { if (open) { setCurrentPw(''); setNewPw(''); setConfirmPw(''); setError(''); } }, [open]); const tooShort = newPw.length > 0 && newPw.length < 8; const mismatch = confirmPw.length > 0 && newPw !== confirmPw; const canSubmit = currentPw.length > 0 && newPw.length >= 8 && newPw === confirmPw; const submit = async () => { if (!canSubmit) { if (!currentPw) setError('Please enter your current password.'); else if (newPw.length < 8) setError('New password must have at least 8 characters.'); else if (newPw !== confirmPw) setError('Passwords do not match.'); return; } setBusy(true); setError(''); try { await authAPI.changePassword(currentPw, newPw); onToast?.('Your password has been updated.', 'success'); onClose(); } catch (err) { setError(err.message); } finally { setBusy(false); } }; return (
setCurrentPw(e.target.value)} className="input-field" autoFocus />
setNewPw(e.target.value)} className={`input-field ${tooShort ? 'border-red-500 focus:ring-red-500' : ''}`} minLength={8} /> {tooShort &&

Minimum 8 characters.

}
setConfirmPw(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); submit(); } }} className={`input-field ${mismatch ? 'border-red-500 focus:ring-red-500' : ''}`} minLength={8} /> {mismatch &&

Passwords do not match.

} {!mismatch && confirmPw.length > 0 && newPw === confirmPw && newPw.length >= 8 && (

Passwords match.

)}
{error &&

{error}

}
); }; export default ChangeMyPasswordModal;