import { Calendar } from "antd";
import "dayjs/locale/ru";
import CalendarCell from "../CalendarCell/CalendarCell.jsx";
import useAppointments from "../../useAppointments.js";
import useAppointmentCalendarUI from "./useAppointmentCalendarUI.js";
import AppointmentsListModal from "../AppointmentsListModal/AppointmentsListModal.jsx";
import dayjs from "dayjs";

const AppointmentsCalendarTab = () => {
    const appointmentsData = useAppointments();
    const appointmentsCalendarUI = useAppointmentCalendarUI(
        appointmentsData.appointments,
        appointmentsData.scheduledAppointments
    );

    const dateCellRender = (value) => {
        const appointmentsForDate = appointmentsCalendarUI.getAppointmentsByListAndDate(
            appointmentsData.appointments,
            value
        );
        const scheduledForDate = appointmentsCalendarUI.getAppointmentsByListAndDate(
            appointmentsData.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={appointmentsCalendarUI.selectedDate}
                onSelect={appointmentsCalendarUI.onSelect}
                onPanelChange={appointmentsCalendarUI.onPanelChange}
                cellRender={dateCellRender}
            />
            <AppointmentsListModal />
        </div>
    );
};

export default AppointmentsCalendarTab;