import {Calendar} from "antd";
import "dayjs/locale/ru";
import CalendarCell from "../CalendarCell/CalendarCell.jsx";
import useAppointmentCalendarUI from "./useAppointmentCalendarUI.js";
import AppointmentsListModal from "../AppointmentsListModal/AppointmentsListModal.jsx";
import dayjs from "dayjs";
import PropTypes from "prop-types";

const AppointmentsCalendarTab = ({currentMonth, onMonthChange, appointments, scheduledAppointments}) => {
    const appointmentsCalendarUI = useAppointmentCalendarUI(appointments, scheduledAppointments);

    const dateCellRender = (value) => {
        const appointmentsForDate = appointmentsCalendarUI.getAppointmentsByListAndDate(
            appointments,
            value
        );
        const scheduledForDate = appointmentsCalendarUI.getAppointmentsByListAndDate(
            scheduledAppointments,
            value,
            true
        );

        const allAppointments = [...appointmentsForDate, ...scheduledForDate].sort((a, b) => {
            const timeA = a.appointment_datetime || a.scheduled_datetime;
            const timeB = b.appointment_datetime || b.scheduled_datetime;
            return dayjs(timeA).diff(dayjs(timeB));
        });

        return (
            <CalendarCell
                allAppointments={allAppointments}
                onCellClick={() => appointmentsCalendarUI.onSelect(value)}
                onItemClick={appointmentsCalendarUI.onOpenAppointmentModal}
            />
        );
    };

    return (
        <div style={appointmentsCalendarUI.calendarContainerStyle}>
            <Calendar
                fullscreen={appointmentsCalendarUI.fullScreenCalendar}
                value={currentMonth} // Используем currentMonth вместо selectedDate
                onSelect={appointmentsCalendarUI.onSelect}
                onPanelChange={(value, mode) => {
                    appointmentsCalendarUI.onPanelChange(value, mode);
                    if (mode === "month") {
                        onMonthChange(value); // Вызываем onMonthChange при смене месяца
                    }
                }}
                cellRender={dateCellRender}
            />
            <AppointmentsListModal/>
        </div>
    );
};

AppointmentsCalendarTab.propTypes = {
    currentMonth: PropTypes.object.isRequired,
    onMonthChange: PropTypes.func.isRequired,
    appointments: PropTypes.array.isRequired,
    scheduledAppointments: PropTypes.array.isRequired,
};

export default AppointmentsCalendarTab;