import {Form, notification} from "antd";
import {useEffect} from "react";
import dayjs from "dayjs";
import validator from "validator";
import {useDispatch, useSelector} from "react-redux";
import {closeModal} from "../../../Redux/Slices/patientsSlice.js";


const usePatientFormModalUI = (onSubmit) => {
    const dispatch = useDispatch();
    const {selectedPatient, isModalVisible} = useSelector(state => state.patientsUI);
    const [form] = Form.useForm();

    useEffect(() => {
        if (isModalVisible) {
            form.resetFields();
            if (selectedPatient) {
                form.setFieldsValue({
                    ...selectedPatient,
                    birthday: selectedPatient.birthday ? dayjs(selectedPatient.birthday, "YYYY-MM-DD") : null,
                });
            }
        }
    }, [isModalVisible, selectedPatient, form]);

    const modalStyle = {
        marginTop: 20,
        marginBottom: 50,
    };
    const modalTitle = selectedPatient ? "Редактировать пациента" : "Добавить пациента";

    const emailValidator = (_, value) => {
        if (value && !validator.isEmail(value)) {
            return Promise.reject("Некорректный email");
        }
        return Promise.resolve();
    };

    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            if (values.birthday) {
                values.birthday = values.birthday.format("YYYY-MM-DD");
            }
            onSubmit(values);
            form.resetFields();
        } catch (error) {
            console.log("Validation Failed:", error);
            notification.error({
                message: "Ошибка валидации",
                description: "Проверьте правильность заполнения полей.",
                placement: "topRight",
            });
        }
    };

    const handleCancel = () => {
        form.resetFields();
        dispatch(closeModal());
    };

    return {
        form,
        modalStyle,
        modalTitle,
        isModalVisible,
        handleOk,
        handleCancel,
        emailValidator,
    }
};

export default usePatientFormModalUI;