import React, {ReactNode, useEffect, useRef, useState} from 'react';
import EventsPopup from "./EventsPopup";
import {Dayjs} from "dayjs";

type CalendarDayProps = {
    day: Dayjs
    events?: any[]
    hasEvent: boolean
    isToday: boolean
    isInMonth: boolean
    onClick: ()=>void
}

const CalendarDay = ({day, isInMonth, isToday, hasEvent, events, onClick}: CalendarDayProps) => {

    const [showEvents, setShowEvents] = useState('')
    const popupRef = useRef(null)
    const dayString = day.format('YYYY-MM-DD')


    // useEffect(() => {
    //     //     const handleClick = (e: any) => {
    //     //
    //     //         if (showEvents) {
    //     //             if (e.source && e.source.current === popupRef.current) return
    //     //             setShowEvents('')
    //     //         }
    //     //     }
    //     //     window.addEventListener('click', handleClick)
    //     //     return () => window.removeEventListener('click', handleClick)
    //     // }, [showEvents]);


    return (
        <td
            className={`calendar-day ${isInMonth && 'inMonth'} ${hasEvent && 'hasEvent'} ${isToday && 'today'}`}
            onClick={onClick}

        >
            <span>
                 {day.date()}
            </span>


            {showEvents === dayString &&
                /*@ts-ignore*/
                <EventsPopup events={events}
                    /*@ts-ignore*/
                             rect ={popupRef!.current!.getBoundingClientRect()}
                             day={day}
                />
            }
        </td>
    );
}

export default CalendarDay;