import React, { useEffect, useState } from "react"; import { Box, Button, Typography, Modal, CircularProgress, } from "@mui/material"; import CloseIcon from "@mui/icons-material/Close"; import { useForm, Controller } from "react-hook-form"; import { useDispatch } from "react-redux"; import { managerList, updateManager } from "../../redux/slices/managerSlice"; // Import the updateManager action import { CustomIconButton, CustomTextField, } from "../AddEditUserModel/styled.css.tsx"; // Custom styled components import { AppDispatch } from "../../redux/store/store.ts"; interface EditManagerModalProps { open: boolean; handleClose: () => void; handleUpdate: ( id: string, name: string, email: string, phone: string, stationId: string ) => Promise; editRow: any; } interface FormData { name: string; email: string; phone: string; stationId: string; } const EditManagerModal: React.FC = ({ open, handleClose, editRow, }) => { const dispatch = useDispatch(); const { control, handleSubmit, formState: { errors }, setValue, reset, } = useForm({ defaultValues: { name: "", email: "", phone: "", stationId: "", }, }); const [loading, setLoading] = useState(false); // Set values if editRow is provided useEffect(() => { if (editRow) { setValue("name", editRow.name); setValue("email", editRow.email); setValue("phone", editRow.phone); setValue("stationId", editRow.stationId); } else { reset(); } }, [editRow, setValue, reset]); const onSubmit = async (data: FormData) => { if (editRow) { try { await dispatch( updateManager({ id: editRow.id, // Manager ID managerData: { name: data.name, email: data.email, phone: data.phone, stationId: data.stationId, }, }) ).unwrap(); // Ensure that it throws an error if the update fails dispatch(managerList()); handleClose(); // Close modal on success reset(); // Reset form fields after submit } catch (error) { console.error(error); // You can handle the error here or show a toast } finally { setLoading(false); // Stop loading state } } }; return ( { if (reason === "backdropClick") { return; } handleClose(); // Close modal when clicking cross or cancel }} aria-labelledby="edit-manager-modal" > {/* Header */} Edit Manager {/* Horizontal Line */} {/* Input Fields (Name, Email, and Phone) */} {/* Manager Name */} Manager Name ( )} /> {/* Email */} Email ( )} /> {/* Phone Number */} Phone Number ( )} /> {/* StationId ( )} /> */} {/* Submit Button */} ); }; export default EditManagerModal;