import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { DayPicker } from "react-day-picker";
import { GetSvgIcon } from "..";
import "react-day-picker/dist/style.css";
import { createPortal } from "react-dom";
import CustomDayContent from "./CustomDayContent";
import "./style.scss";
const DatePicker = ({ disabledUntil, disableWeekends = false, onDateSelected, initialValue, eventsData, timezone, customRootElem, }) => {
    const [calenderActive, setCalenderActive] = useState(false);
    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", { className: "cancelButton", onClick: () => setCalenderActive(false), children: "Cancel" }), _jsx("button", { className: "okButton", onClick: () => setCalenderActive(false), children: "Ok" })] })] }));
    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 isWeekend = (date) => {
        const day = date.getDay();
        return day === 0 || day === 6;
    };
    const isDateDisabled = (date) => {
        let disabledConditions = [];
        disabledConditions.push(date <= yesterday);
        if (disabledUntil) {
            disabledConditions.push(date <= new Date(disabledUntil));
        }
        if (disableWeekends) {
            disabledConditions.push(isWeekend(date));
        }
        return disabledConditions.some((bool) => bool);
    };
    const [dropdownPosition, setDropdownPosition] = useState({ x: 0, y: 0, direction: "top" });
    const dropdownRef = useRef(null);
    const rootElem = useRef(document.getElementById("root"));
    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;
            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) {
            // Ensure the calendar opens on the month of the selected date
            setSelectedMonth(selectedDate);
        }
        calculateDropdownPosition();
        setCalenderActive(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 (selectedDate &&
            (selectedDate.getDate() !== initialValue?.getDate() ||
                selectedDate.getMonth() !== initialValue?.getMonth() ||
                selectedDate.getFullYear() !== initialValue?.getFullYear())) {
            onDateSelected(selectedDate);
        }
    }, [selectedDate, initialValue, onDateSelected]);
    return (_jsxs("div", { className: "datePickerDropdown--Active", ref: mainRef, children: [_jsxs("button", { className: "datePickerDropdown-Button", onClick: (e) => {
                    e.stopPropagation();
                    handleOpen(!calenderActive);
                }, 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" })] }), calenderActive &&
                (!!rootElem.current || !!customRootElem) &&
                createPortal(_jsx("div", { className: `${calenderActive ? "" : "datePickerCalender--hidden"} datePickerCalender-Container`, ref: dropdownRef, style: {
                        [dropdownPosition.direction]: dropdownPosition?.y,
                        left: dropdownPosition?.x,
                    }, children: _jsx(DayPicker, { disabled: isDateDisabled, disableNavigation: true, mode: "single", month: selectedMonth, modifiersClassNames: {
                            selected: "datePicker-mySelected",
                            today: "datePicker-myToday",
                        }, selected: selectedDate, onSelect: (...props) => {
                            props?.[3]?.stopPropagation?.();
                            setSelectedDate(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 || rootElem.current)] }));
};
export default DatePicker;
