import {useGetAppointmentsQuery, useGetUpcomingAppointmentsQuery} from "../../../Api/appointmentsApi.js";
import {
    useGetScheduledAppointmentsQuery,
    useGetUpcomingScheduledAppointmentsQuery
} from "../../../Api/scheduledAppointmentsApi.js";
import {useGetAllPatientsQuery} from "../../../Api/patientsApi.js";
import {notification} from "antd";
import {useEffect} from "react";
import {useDispatch, useSelector} from "react-redux";
import {
    setSelectedAppointment,
    setSelectedScheduledAppointment,
    openModal as openAppointmentsListModal,
    openScheduledModal,
} from "../../../Redux/Slices/appointmentsSlice.js";
import {
    openModal as openPatientModal,
} from "../../../Redux/Slices/patientsSlice.js";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import isBetween from "dayjs/plugin/isBetween";
import {useGetAppointmentTypesQuery} from "../../../Api/appointmentTypesApi.js";

dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(isBetween);

const useHomePage = () => {
    const dispatch = useDispatch();
    const {userData} = useSelector((state) => state.auth);

    const startDate = dayjs().startOf('month').format('YYYY-MM-DD');
    const endDate = dayjs().endOf('month').format('YYYY-MM-DD');

    const {
        data: appointments = [],
        isLoading: isLoadingAppointments,
        isError: isErrorAppointments,
    } = useGetAppointmentsQuery({doctor_id: userData.id, start_date: startDate, end_date: endDate}, {
        pollingInterval: 60000,
        skip: !userData.id,
    });

    const {
        data: scheduledAppointments = [],
        isLoading: isLoadingScheduledAppointments,
        isError: isErrorScheduledAppointments,
    } = useGetScheduledAppointmentsQuery({doctor_id: userData.id, start_date: startDate, end_date: endDate}, {
        pollingInterval: 60000,
        skip: !userData.id,
    });

    const {
        data: upcomingAppointments = [],
        isLoading: isLoadingUpcomingAppointments,
        isError: isErrorUpcomingAppointments,
    } = useGetUpcomingAppointmentsQuery(userData.id, {
        pollingInterval: 60000,
        skip: !userData.id,
    });

    const {
        data: upcomingScheduledAppointments = [],
        isLoading: isLoadingUpcomingScheduledAppointments,
        isError: isErrorUpcomingScheduledAppointments,
    } = useGetUpcomingScheduledAppointmentsQuery(userData.id, {
        pollingInterval: 60000,
        skip: !userData.id,
    });

    const {
        data: patients = [],
        isLoading: isLoadingPatients,
        isError: isErrorPatients,
    } = useGetAllPatientsQuery(undefined, {
        pollingInterval: 60000,
        skip: !userData.id,
    });

    const {
        data: appointmentTypes = [],
        isLoading: isLoadingAppointmentTypes,
        isError: isErrorAppointmentTypes,
    } = useGetAppointmentTypesQuery(undefined, {
        pollingInterval: 60000,
        skip: !userData.id,
    });

    useEffect(() => {
        if (isErrorAppointments) {
            notification.error({
                message: "Ошибка",
                description: "Ошибка загрузки приемов.",
                placement: "topRight",
            });
        }
        if (isErrorScheduledAppointments) {
            notification.error({
                message: "Ошибка",
                description: "Ошибка загрузки запланированных приемов.",
                placement: "topRight",
            });
        }
        if (isErrorUpcomingAppointments) {
            notification.error({
                message: "Ошибка",
                description: "Ошибка загрузки предстоящих приемов.",
                placement: "topRight",
            });
        }
        if (isErrorUpcomingScheduledAppointments) {
            notification.error({
                message: "Ошибка",
                description: "Ошибка загрузки предстоящих запланированных приемов.",
                placement: "topRight",
            });
        }
        if (isErrorPatients) {
            notification.error({
                message: "Ошибка",
                description: "Ошибка загрузки пациентов.",
                placement: "topRight",
            });
        }
        if (isErrorAppointmentTypes) {
            notification.error({
                message: "Ошибка",
                description: "Ошибка загрузки типов приемов.",
                placement: "topRight",
            });
        }
    }, [
        isErrorAppointments,
        isErrorScheduledAppointments,
        isErrorUpcomingAppointments,
        isErrorUpcomingScheduledAppointments,
        isErrorPatients,
        isErrorAppointmentTypes
    ]);

    const handleEventClick = (event) => {
        if (event.appointment_datetime) {
            dispatch(setSelectedAppointment(event));
        } else {
            dispatch(setSelectedScheduledAppointment(event));
        }
    };

    const handleCreateAppointment = () => {
        dispatch(openAppointmentsListModal());
    };

    const handleCreateScheduledAppointment = () => {
        dispatch(openScheduledModal());
    };

    const handleCreatePatient = () => {
        dispatch(openPatientModal());
    };

    return {
        patients,
        appointments,
        scheduledAppointments,
        upcomingAppointments,
        upcomingScheduledAppointments,
        appointmentTypes,
        isLoading:
            isLoadingAppointments ||
            isLoadingScheduledAppointments ||
            isLoadingUpcomingAppointments ||
            isLoadingUpcomingScheduledAppointments ||
            isLoadingPatients ||
            isLoadingAppointmentTypes,
        isError:
            isErrorAppointments ||
            isErrorScheduledAppointments ||
            isErrorUpcomingAppointments ||
            isErrorUpcomingScheduledAppointments ||
            isErrorPatients ||
            isErrorAppointmentTypes,
        handleEventClick,
        handleCreateAppointment,
        handleCreateScheduledAppointment,
        handleCreatePatient,
    };
};

export default useHomePage;