import {useDispatch, useSelector} from "react-redux";
import {closeScheduledModal} from "../../../Redux/Slices/appointmentsSlice.js";
import {useMemo, useState} from "react";
import dayjs from "dayjs";
import {notification} from "antd";


const useScheduledAppointmentFormModalUI = (patients, createScheduledAppointment) => {
    const dispatch = useDispatch();

    const {
        scheduledModalVisible,
    } = useSelector(state => state.appointmentsUI);

    const [searchPatientString, setSearchPatientString] = useState('');
    const [selectedPatient, setSelectedPatient] = useState(null);
    const [selectedDateTime, setSelectedDateTime] = useState(dayjs(new Date()).add(1, 'day'));
    const [selectedAppointmentType, setSelectedAppointmentType] = useState(null);

    const handleCreateScheduledAppointment = async () => {
        try {
            const data = {
                scheduled_datetime: selectedDateTime.format('YYYY-MM-DD HH:mm:ss'),
                patient_id: selectedPatient.id,
                type_id: selectedAppointmentType
            };

            await createScheduledAppointment(data).unwrap();
            notification.success({
                message: 'Прием создан',
                placement: 'topRight',
                description: 'Прием успешно запланирован.',
            });

            setSelectedPatient(null);
            setSelectedDateTime(dayjs(new Date()).add(1, 'day'));
            setSelectedAppointmentType(null);

            dispatch(closeScheduledModal());
        } catch (error) {
            notification.error({
                message: 'Ошибка',
                description: error.data?.message || 'Не удалось сохранить прием.',
                placement: 'topRight',
            });
        }
    };

    const filteredPatients = useMemo(() => patients.filter((patient) => {
        const searchLower = searchPatientString.toLowerCase();

        return Object.values(patient)
            .filter(value => typeof value === "string")
            .some(value => value.toLowerCase().includes(searchLower));
    }), [patients, searchPatientString]);

    const handleSetDateTime = (date) => {
        setSelectedDateTime(date);
    };

    const handleSetSearchPatientString = (e) => {
        setSearchPatientString(e.target.value);
    };

    const handleSetSelectedAppointmentType = (type) => {
        setSelectedAppointmentType(type);
    };

    const getDateString = (date) => {
        return date ? dayjs(date).format('DD.MM.YYYY') : 'Не указано';
    };

    const getSelectedPatientBirthdayString = () => {
        return selectedPatient ? getDateString(selectedPatient.birthday) : 'Не выбран';
    };

    const resetPatient = () => {
        setSelectedPatient(null);
    };

    const searchInputStyle = {marginBottom: 16};

    const modalWidth = 700;

    const handleCancelModal = () => {
        dispatch(closeScheduledModal());
    };

    const datePickerStyle = {marginBottom: 16};
    const buttonStyle = {marginTop: 8};

    return {
        scheduledModalVisible,
        filteredPatients,
        selectedPatient,
        setSelectedPatient,
        modalWidth,
        selectedDateTime,
        searchInputStyle,
        datePickerStyle,
        buttonStyle,
        selectedAppointmentType,
        handleCancelModal,
        handleSetSearchPatientString,
        resetPatient,
        getSelectedPatientBirthdayString,
        getDateString,
        handleSetDateTime,
        handleSetSelectedAppointmentType,
        handleCreateScheduledAppointment,
    }
};

export default useScheduledAppointmentFormModalUI