import { useDispatch, useSelector } from "react-redux";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import { Grid } from "antd";
import {
    openAppointmentsListModal,
    setSelectedAppointment,
    setSelectedScheduledAppointment,
    setSelectedDate,
} from "../../../../../Redux/Slices/appointmentsSlice.js";

dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.tz.setDefault("Europe/Moscow");

const { useBreakpoint } = Grid;

const useAppointmentCalendarUI = (appointments, scheduledAppointments) => {
    const dispatch = useDispatch();
    const selectedDate = dayjs.tz(useSelector((state) => state.appointmentsUI.selectedDate), "Europe/Moscow");

    const screens = useBreakpoint();
    const fullScreenCalendar = !screens.xs;

    const calendarContainerStyle = { padding: 20 };

    const onSelect = (date) => {
        const selectedDateStr = date.format("YYYY-MM-DD");
        const appointmentsForDate = appointments.filter((app) =>
            dayjs(app.appointment_datetime).format("YYYY-MM-DD") === selectedDateStr
        );
        const scheduledForDate = scheduledAppointments.filter((app) =>
            dayjs(app.scheduled_datetime).format("YYYY-MM-DD") === selectedDateStr
        );
        dispatch(openAppointmentsListModal([...appointmentsForDate, ...scheduledForDate]));
        dispatch(setSelectedDate(date.toISOString()));
    };

    const onPanelChange = (date) => {
        dispatch(setSelectedDate(date.startOf("month").toISOString()));
    };

    const onOpenAppointmentModal = (appointment) => {
        if (appointment.appointment_datetime) {
            dispatch(setSelectedAppointment(appointment));
        } else {
            dispatch(setSelectedScheduledAppointment(appointment));
        }
    };

    const getAppointmentsByListAndDate = (list, value, isScheduled = false) => {
        const date = value.format("YYYY-MM-DD");
        return list.filter((app) =>
            dayjs(isScheduled ? app.scheduled_datetime : app.appointment_datetime).format("YYYY-MM-DD") === date
        );
    };

    return {
        selectedDate,
        fullScreenCalendar,
        calendarContainerStyle,
        onSelect,
        onPanelChange,
        getAppointmentsByListAndDate,
        onOpenAppointmentModal,
    };
};

export default useAppointmentCalendarUI;