'use client'; import { useState } from 'react'; import { useMutation } from '@tanstack/react-query'; import { CheckCircle2 } from 'lucide-react'; import Modal from '@/components/ui/Modal'; import ActionButton from '@/components/ui/ActionButton'; import { iamAuthApi } from '@/lib/api/auth'; interface ChangePasswordModalProps { isOpen: boolean; onClose: () => void; } export default function ChangePasswordModal({ isOpen, onClose }: ChangePasswordModalProps) { const [oldPassword, setOldPassword] = useState(''); const [newPassword, setNewPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [error, setError] = useState(''); const [success, setSuccess] = useState(false); const changePasswordMutation = useMutation({ mutationFn: () => iamAuthApi.changePassword({ oldPassword, newPassword, confirmPassword }), onSuccess: () => { setSuccess(true); setTimeout(() => handleClose(), 1500); }, onError: (err: any) => { const msg = err.response?.data?.message || ''; if (err.response?.status === 401) { setError('Current password is incorrect.'); } else if (msg === 'new_password_same_as_old') { setError('New password must be different from the current password.'); } else if (msg === 'new_passwords_do_not_match') { setError('New passwords do not match.'); } else { setError(msg || 'Failed to change password. Please try again.'); } }, }); const handleClose = () => { setOldPassword(''); setNewPassword(''); setConfirmPassword(''); setError(''); setSuccess(false); onClose(); }; const handleSubmit = () => { setError(''); if (newPassword.length < 6) { setError('New password must be at least 6 characters.'); return; } if (newPassword !== confirmPassword) { setError('New passwords do not match.'); return; } if (newPassword === oldPassword) { setError('New password must be different from the current password.'); return; } changePasswordMutation.mutate(); }; return (
{ e.preventDefault(); handleSubmit(); }} className="space-y-4" > {success && (

Password changed successfully.

)} {error && (

{error}

)}
{ setOldPassword(e.target.value); setError(''); }} placeholder="Enter current password" autoComplete="current-password" required />
{ setNewPassword(e.target.value); setError(''); }} placeholder="Enter new password" autoComplete="new-password" minLength={6} required />
{ setConfirmPassword(e.target.value); setError(''); }} placeholder="Re-enter new password" autoComplete="new-password" minLength={6} required />
Cancel Change Password
); }