import {closeModal} from "../../../Redux/Slices/patientsSlice.js";
import {notification} from "antd";
import {useDispatch, useSelector} from "react-redux";
import {useAddPatientMutation, useUpdatePatientMutation} from "../../../Api/patientsApi.js";


const usePatientFormModal = () => {
    const dispatch = useDispatch();

    const [addPatient] = useAddPatientMutation();
    const [updatePatient] = useUpdatePatientMutation();

    const {
        selectedPatient,
    } = useSelector(state => state.patientsUI);

    const handleModalSubmit = async (patientData) => {
        dispatch(closeModal());

        try {
            if (selectedPatient) {
                await updatePatient({ id: selectedPatient.id, ...patientData }).unwrap();
                notification.success({
                    message: "Пациент обновлён",
                    description: `Данные пациента ${patientData.first_name} ${patientData.last_name} успешно обновлены.`,
                    placement: "topRight",
                });
            } else {
                await addPatient(patientData).unwrap();
                notification.success({
                    message: "Пациент добавлен",
                    description: `Пациент ${patientData.first_name} ${patientData.last_name} успешно добавлен.`,
                    placement: "topRight",
                });
            }
        } catch (error) {
            notification.error({
                message: "Ошибка",
                description: error.data?.message || "Произошла ошибка при сохранении",
                placement: "topRight",
            });
        }
    };

    return {
        handleModalSubmit,
    };
};

export default usePatientFormModal;