import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { DayPicker } from "react-day-picker";
import "react-day-picker/dist/style.css";
import { createPortal } from "react-dom";
import CustomDayContent from "./CustomDayContent";
import "./style.scss";
import GetSvgIcon from "../../GetSvgIcon";
function DatePicker({ onDateSelected, initialValue, eventsData, timezone, customRootElem, isOpen, }) {
    const [calendarActive, setCalendarActive] = useState(!!isOpen);
    const [selectedMonth, setSelectedMonth] = useState(new Date());
    const [selectedDate, setSelectedDate] = useState(initialValue || new Date());
    const selectedDateMonth = (selectedDate && selectedDate.getMonth() + 1) || 1;
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    const footer = (_jsxs("div", { className: "footerContainer", children: [!!timezone && _jsx("div", { className: "timezone", children: timezone }), _jsxs("div", { className: "button-container", children: [_jsx("button", { type: "button", className: "okButton", onClick: () => setCalendarActive(false), children: "OK" }), _jsx("button", { type: "button", className: "cancelButton", onClick: () => setCalendarActive(false), children: "Cancel" })] })] }));
    const handlePrevMonthClick = (e) => {
        e.stopPropagation();
        const newDate = new Date(selectedMonth);
        newDate.setMonth(selectedMonth.getMonth() - 1);
        setSelectedMonth(newDate);
    };
    const handleNextMonthClick = (e) => {
        e.stopPropagation();
        const newDate = new Date(selectedMonth);
        newDate.setMonth(selectedMonth.getMonth() + 1);
        setSelectedMonth(newDate);
    };
    const formatCaption = (date) => {
        const months = date.toLocaleString("en-US", { month: "long" });
        return (_jsxs("div", { className: "datePicker-customCaption", children: [_jsx("span", { className: "datePicker-prevMonthArrow", onClick: handlePrevMonthClick, children: _jsx(GetSvgIcon, { iconType: "arrowLeft", iconSize: "32" }) }), months, " ", date.getFullYear(), _jsx("span", { className: "datePicker-nextMonthArrow", onClick: handleNextMonthClick, children: _jsx(GetSvgIcon, { iconType: "arrowRight", iconSize: "32" }) })] }));
    };
    const formatWeekday = (date) => {
        const weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
        return weekdays[date.getDay()];
    };
    const [dropdownPosition, setDropdownPosition] = useState({ x: 0, y: 0, direction: "top" });
    const dropdownRef = useRef(null);
    const mainRef = useRef(null);
    const calculateDropdownPosition = () => {
        if (mainRef.current) {
            const elemRect = mainRef.current.getBoundingClientRect();
            let offsetY = elemRect.y + elemRect.height + 8;
            let direction = "top";
            const offsetX = elemRect.x - elemRect.width - 90;
            if (450 > window.innerHeight - elemRect.y) {
                direction = "bottom";
                offsetY = window.innerHeight - elemRect.y + 8;
            }
            setDropdownPosition({ y: offsetY, x: offsetX, direction });
        }
    };
    const handleOpen = (open) => {
        if (open && selectedDate) {
            setSelectedMonth(selectedDate);
        }
        calculateDropdownPosition();
        setCalendarActive(open);
    };
    const handleClickOutside = (e) => {
        const target = e.target;
        if (dropdownRef.current &&
            mainRef.current &&
            target !== dropdownRef.current &&
            !dropdownRef.current.contains(target) &&
            !mainRef.current.contains(target)) {
            handleOpen(false);
        }
    };
    useEffect(() => {
        window.addEventListener("click", handleClickOutside);
        window.addEventListener("wheel", calculateDropdownPosition);
        return () => {
            window.removeEventListener("click", handleClickOutside);
            window.removeEventListener("wheel", calculateDropdownPosition);
        };
    }, []);
    useEffect(() => {
        if (initialValue) {
            setSelectedDate(initialValue);
        }
    }, [initialValue]);
    useEffect(() => {
        if (calendarActive && !isOpen) {
            setCalendarActive(false);
        }
    }, [isOpen]);
    return (_jsxs("div", { className: "datePickerDropdown--Active", ref: mainRef, children: [_jsxs("button", { className: "datePickerDropdown-Button", onClick: () => {
                    handleOpen(true);
                }, children: [_jsx("p", { children: selectedDate
                            ? `${selectedDateMonth < 10
                                ? `0${selectedDateMonth}`
                                : selectedDateMonth}/${selectedDate.getDate() < 10
                                ? `0${selectedDate.getDate()}`
                                : selectedDate.getDate()}/${selectedDate.getFullYear()}`
                            : "Date" }), _jsx(GetSvgIcon, { iconType: "calendar", iconSize: "16" })] }), calendarActive &&
                createPortal(_jsx("div", { className: `${calendarActive ? "" : "datePickerCalender--hidden"} datePickerCalender-Container`, ref: dropdownRef, style: {
                        [dropdownPosition.direction]: dropdownPosition?.y,
                        left: dropdownPosition?.x,
                    }, children: _jsx(DayPicker, { disableNavigation: true, mode: "single", month: selectedMonth, modifiersClassNames: {
                            selected: "datePicker-mySelected",
                            today: "datePicker-myToday",
                        }, selected: selectedDate, onSelect: (...props) => {
                            if (props?.[0] && props[0].getTime() <= new Date().getTime()) {
                                setSelectedDate(props[0]);
                                onDateSelected(props[0]);
                            }
                        }, footer: footer, formatters: { formatCaption, formatWeekdayName: formatWeekday }, showOutsideDays: true, components: {
                            DayContent: (props) => (_jsx(CustomDayContent, { date: props.date, displayMonth: props.displayMonth, eventsData: eventsData })),
                        }, classNames: { day: "datepicker-day-cell" } }) }), customRootElem || document.body)] }));
}
export default DatePicker;
