import React, { useState } from "react"; import Input from "../Input/Input"; import Button from "../Input/Button"; interface ResetPasswordData { newPassword: string; confirmNewPassword: string; } interface ResetPasswordErrors { newPasswordError?: string; confirmNewPasswordError?: string; } interface SubmitProps { onSubmit: (success: boolean) => void; token: string; } const PasswordResetForm: React.FC = ({ onSubmit, token }) => { const [errors, setErrors] = useState({}); const [resetData, setResetData] = useState({ newPassword: "", confirmNewPassword: "", }); const handlePasswordChange = (e: React.ChangeEvent) => { const { name, value } = e.target; setResetData((prev) => ({ ...prev, [name]: value, })); }; const validateResetForm = (): boolean => { const newErrors: ResetPasswordErrors = {}; Object.keys(resetData).forEach((key) => { if (!resetData[key as keyof ResetPasswordData]) { newErrors[key as keyof ResetPasswordErrors] = "Confirm your password"; } }); if (resetData.newPassword.length < 8) { newErrors.newPasswordError = "Password must be at least 8 characters long"; } if (resetData.newPassword !== resetData.confirmNewPassword) { newErrors.confirmNewPasswordError = "Passwords do not match"; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (validateResetForm()) { try { const response = await fetch( `/api/user/reset_password/${token}/${resetData.newPassword}`, { method: "POST", headers: { "Content-Type": "application/json", }, credentials: "include", body: JSON.stringify(resetData), } ); if (!response.ok) { const data = await response.json(); onSubmit(false); throw new Error( data.error || "An error has occurred while resetting" ); } else { onSubmit(true); } } catch (error: any) { console.error("Password reset error:", error.message); setErrors((prev) => ({ ...prev, general: error.message || "An unexpected error occurred.", })); } } }; return (
{errors.confirmNewPasswordError && (

{errors.confirmNewPasswordError}

)}
); }; export default PasswordResetForm;