import {Calendar, Grid, ConfigProvider, Badge, Modal} from "antd";
import {useState} from "react";
import dayjs from "dayjs";
import 'dayjs/locale/ru';
import locale from 'antd/es/locale/ru_RU';
import updateLocale from 'dayjs/plugin/updateLocale';
import PropTypes from "prop-types";

const {useBreakpoint} = Grid;

dayjs.extend(updateLocale);
dayjs.updateLocale('ru', {
    weekStart: 1
});

const AppointmentsCalendarPage = ({appointments, scheduledAppointments}) => {
    const screens = useBreakpoint();
    const [selectedDate, setSelectedDate] = useState(dayjs(new Date()));
    const [modalVisible, setModalVisible] = useState(false);
    const [selectedAppointments, setSelectedAppointments] = useState([]);

    const dateCellRender = (value) => {
        const date = value.format('YYYY-MM-DD');
        const appointmentsForDate = appointments.filter(app =>
            dayjs(app.appointment_datetime).format('YYYY-MM-DD') === date
        );
        const scheduledForDate = scheduledAppointments.filter(app =>
            dayjs(app.scheduled_datetime).format('YYYY-MM-DD') === date
        );

        return (
            <ul style={{listStyle: 'none', padding: 0}}>
                {appointmentsForDate.map(app => (
                    <li key={app.id}>
                        <Badge status="success" text={`Прием ${dayjs(app.appointment_datetime).format('HH:mm')}`}/>
                    </li>
                ))}
                {scheduledForDate.map(app => (
                    <li key={app.id}>
                        <Badge status="processing"
                               text={`Запланировано ${dayjs(app.scheduled_datetime).format('HH:mm')}`}/>
                    </li>
                ))}
            </ul>
        );
    };

    const onSelect = (date) => {
        setSelectedDate(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
        );
        setSelectedAppointments([...appointmentsForDate, ...scheduledForDate]);
        setModalVisible(true);
    };

    return (
        <ConfigProvider locale={locale}>
            <div style={{padding: 20}}>
                <Calendar
                    fullscreen={!screens.xs}
                    value={selectedDate}
                    onSelect={onSelect}
                    cellRender={dateCellRender}
                />
                <Modal
                    title={`Приемы на ${selectedDate.format('DD.MM.YYYY')}`}
                    open={modalVisible}
                    onCancel={() => setModalVisible(false)}
                    footer={null}
                >
                    {selectedAppointments.map(app => (
                        <div key={app.id}>
                            <p>{app.appointment_datetime ? 'Прием' : 'Запланировано'}: {dayjs(app.appointment_datetime || app.scheduled_datetime).format('HH:mm')}</p>
                            <p>Пациент: {app.patient?.name || 'Не указан'}</p>
                            <p>Врач: {app.doctor?.name || 'Не указан'}</p>
                            <p>Тип: {app.type?.name || 'Не указан'}</p>
                            {app.results && <p>Результаты: {app.results}</p>}
                            <hr/>
                        </div>
                    ))}
                </Modal>
            </div>
        </ConfigProvider>
    );
};

AppointmentsCalendarPage.propTypes = {
    appointments: PropTypes.arrayOf(
        PropTypes.shape({
            id: PropTypes.number.isRequired,
            results: PropTypes.string,
            days_until_the_next_appointment: PropTypes.number,
            appointment_datetime: PropTypes.string.isRequired,
            patient: PropTypes.shape({
                first_name: PropTypes.string,
                last_name: PropTypes.string,
                patronymic: PropTypes.string,
                birthday: PropTypes.string,
                address: PropTypes.string,
                email: PropTypes.string,
                phone: PropTypes.string,
                diagnosis: PropTypes.string,
                correction: PropTypes.string,
            }),
            doctor: PropTypes.shape({
                last_name: PropTypes.string,
                first_name: PropTypes.string,
                login: PropTypes.string,
            }),
            type: PropTypes.shape({
                title: PropTypes.string,
            })
        })
    ),
    scheduledAppointments: PropTypes.arrayOf(
        PropTypes.shape(
            {
                id: PropTypes.number.isRequired,
                scheduled_datetime: PropTypes.string.isRequired,
                patient: PropTypes.shape({
                    first_name: PropTypes.string,
                    last_name: PropTypes.string,
                    patronymic: PropTypes.string,
                    birthday: PropTypes.string,
                    address: PropTypes.string,
                    email: PropTypes.string,
                    phone: PropTypes.string,
                    diagnosis: PropTypes.string,
                    correction: PropTypes.string,
                }),
                doctor: PropTypes.shape({
                    last_name: PropTypes.string,
                    first_name: PropTypes.string,
                    login: PropTypes.string,
                }),
                type: PropTypes.shape({
                    title: PropTypes.string,
                }),
            }
        )
    )
};

export default AppointmentsCalendarPage;
