import { useEffect, useRef, useState } from "react";
import dayjs from "dayjs";

const useCalendarCellUI = () => {
    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();
    }, []);

    // Styles
    const containerStyle = {
        height: "100%",
        cursor: isCompressed ? "pointer" : "default",
        position: "relative",
    };

    const listStyle = {
        padding: 0,
        margin: 0,
    };

    const columnStyle = {
        overflowX: "hidden",
    };

    const tagStyle = {
        margin: "2px 2px 0 0",
        cursor: "pointer",
        width: "95%",
        minHeight: 30,
        display: "flex",
        alignItems: "center",
        overflow: "hidden",
    };

    const badgeTextStyle = {
        whiteSpace: "nowrap",
        overflow: "hidden",
        textOverflow: "ellipsis",
        display: "inline-block",
        width: "100%",
    };

    const compressedCountStyle = {
        position: "absolute",
        top: 2,
        right: 2,
        fontSize: 10,
        fontWeight: "bold",
        color: "#1890ff",
    };

    // Static configuration
    const labels = {
        pastAppointment: "Прошедший прием",
        scheduledAppointment: "Запланированный прием",
        notSpecified: "Не указан",
    };

    // Formatting functions
    const getAppointmentTime = (datetime) => {
        return datetime ? dayjs(datetime).format("HH:mm") : labels.notSpecified;
    };

    const getTooltipTitle = (app) => {
        const type = app.appointment_datetime ? labels.pastAppointment : labels.scheduledAppointment;
        return `${type}: ${getAppointmentTime(app.appointment_datetime || app.scheduled_datetime)}`;
    };

    const getBadgeText = (app) => {
        const time = getAppointmentTime(app.appointment_datetime || app.scheduled_datetime);
        const patientName = app.patient
            ? `${app.patient.last_name || ""} ${app.patient.first_name || ""}`.trim()
            : labels.notSpecified;
        return `${time} ${patientName}`;
    };

    const getTagColor = (isPast) => {
        return isPast ? "green" : "blue";
    };

    const getBadgeStatus = (isPast) => {
        return isPast ? "success" : "processing";
    };

    return {
        containerRef,
        isCompressed,
        containerStyle,
        listStyle,
        columnStyle,
        tagStyle,
        badgeTextStyle,
        compressedCountStyle,
        labels,
        getTooltipTitle,
        getBadgeText,
        getTagColor,
        getBadgeStatus,
    };
};

export default useCalendarCellUI;