import {useEffect, useRef, useState} from "react";
import {Badge, Col, Tag, Tooltip} from "antd";
import dayjs from "dayjs";
import PropTypes from "prop-types";
import {AppointmentPropType} from "../../Types/appointmentPropType.js";
import {ScheduledAppointmentPropType} from "../../Types/scheduledAppointmentPropType.js";

const CalendarCell = ({allAppointments, onCellClick, onItemClick}) => {
    const containerRef = useRef(null);
    const [isCompressed, setIsCompressed] = useState(false);
    const COMPRESSION_THRESHOLD = 70;

    useEffect(() => {
        if (!containerRef.current) return;

        const observer = new ResizeObserver((entries) => {
            const width = entries[0].contentRect.width;
            setIsCompressed(width < COMPRESSION_THRESHOLD);
        });

        observer.observe(containerRef.current);
        return () => observer.disconnect();
    }, []);

    return (
        <div
            ref={containerRef}
            onClick={isCompressed ? onCellClick : undefined}
            style={{
                height: "100%",
                cursor: isCompressed ? "pointer" : "default",
                position: "relative",
            }}
        >
            {!isCompressed && (
                <ul style={{padding: 0, margin: 0}}>
                    {allAppointments.map((app) => (
                        <Col key={app.id} style={{overflowX: "hidden"}}>
                            <Tooltip
                                title={`${
                                    app.appointment_datetime ? "Прошедший прием" : "Запланированный прием"
                                }: ${dayjs(app.appointment_datetime || app.scheduled_datetime).format("HH:mm")}`}
                            >
                                <Tag
                                    color={app.appointment_datetime ? "green" : "blue"}
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        onItemClick(app);
                                    }}
                                    style={{
                                        margin: "2px 2px 0 0",
                                        cursor: "pointer",
                                        width: "95%",
                                        minHeight: 30,
                                        display: "flex",
                                        alignItems: "center",
                                        overflow: "hidden",
                                    }}
                                >
                                    <Badge
                                        status={app.appointment_datetime ? "success" : "processing"}
                                        text={
                                            <span
                                                style={{
                                                    whiteSpace: "nowrap",
                                                    overflow: "hidden",
                                                    textOverflow: "ellipsis",
                                                    display: "inline-block",
                                                    width: "100%",
                                                }}
                                            >
                        {dayjs(app.appointment_datetime || app.scheduled_datetime).format("HH:mm") +
                            ` ${app.patient?.last_name || ""} ${app.patient?.first_name || ""}`}
                      </span>
                                        }
                                    />
                                </Tag>
                            </Tooltip>
                        </Col>
                    ))}
                </ul>
            )}
            {isCompressed && (
                <div
                    style={{
                        position: "absolute",
                        top: 2,
                        right: 2,
                        fontSize: 10,
                        fontWeight: "bold",
                        color: "#1890ff",
                    }}
                >
                    {allAppointments.length > 0 && `+${allAppointments.length}`}
                </div>
            )}
        </div>
    );
};

CalendarCell.propTypes = {
    allAppointments: PropTypes.arrayOf(
        PropTypes.oneOfType([AppointmentPropType, ScheduledAppointmentPropType])
    ).isRequired,
    onCellClick: PropTypes.func.isRequired,
    onItemClick: PropTypes.func.isRequired,
};

export default CalendarCell;