import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { GetSvgIcon } from "..";
import { createPortal } from "react-dom";
import "./style.scss";
const TimePicker = ({ hourValue, minuteValue, selectedTime, disableBefore, alwaysShowTime, timezone, onTimePicked, }) => {
    const [timeDialActive, setTimeDialActive] = useState(false);
    const [timeDone, setTimeDone] = useState(false);
    const hours = Array.from(Array(12).keys()).map((hour) => {
        const hourString = hour < 9 ? `0${hour + 1}` : `${hour + 1}`;
        return hourString;
    });
    const minutes = Array.from(Array(60).keys()).map((minute) => {
        const minString = minute <= 9 ? `0${minute}` : `${minute}`;
        return minString;
    });
    const amOrPm = ["AM", "PM"];
    const [selectedHour, setSelectedHour] = useState(String(hourValue || 1));
    const [selectedMinute, setSelectedMinute] = useState(String(minuteValue || 0));
    const [timeType, setTimeType] = useState(selectedTime || "AM");
    const getDisabledHours = () => {
        if (!disableBefore) {
            return {
                AM: [],
                PM: [],
            };
        }
        const disabledPmTime = [];
        const disabledAmTime = [];
        const currentTime = new Date();
        const minHour = new Date(disableBefore).getHours();
        const currentHour = currentTime.getHours();
        const currentPeriod = currentHour < 12 ? "AM" : "PM";
        if (minHour > 12) {
            disabledPmTime.push(...Array.from({ length: minHour - 12 }, (_, hour) => hour < 9 ? `0${hour + 1}` : `${hour + 1}`));
            disabledAmTime.push(...Array.from({ length: 12 }, (_, hour) => hour < 9 ? `0${hour + 1}` : `${hour + 1}`));
        }
        else {
            disabledAmTime.push(...Array.from({ length: minHour }, (_, hour) => hour < 9 ? `0${hour + 1}` : `${hour + 1}`));
        }
        if (currentPeriod === "AM") {
            if (currentHour === minHour) {
                disabledAmTime.pop();
            }
        }
        else {
            if (currentHour === minHour) {
                disabledPmTime.pop();
            }
        }
        return {
            PM: disabledPmTime,
            AM: disabledAmTime,
        };
    };
    const disabledHours = getDisabledHours();
    const getDisabledMinutes = () => {
        if (!disableBefore) {
            return {
                AM: [],
                PM: [],
            };
        }
        const disabledPmMinutes = [];
        const disabledAmMinutes = [];
        const disableBeforeDate = new Date(disableBefore);
        const minHour = disableBeforeDate.getHours();
        const minMinute = disableBeforeDate.getMinutes();
        let finalHour = Number(selectedHour);
        if (timeType === "PM" && finalHour !== 12) {
            finalHour += 12;
        }
        else if (timeType === "AM" && finalHour === 12) {
            finalHour = 0;
        }
        if (finalHour !== disableBefore.getHours()) {
            return {
                AM: [],
                PM: [],
            };
        }
        if (minHour < 12 && Number(selectedHour) === minHour) {
            disabledAmMinutes.push(...Array.from({ length: minMinute }, (_, minute) => minute <= 9 ? `0${minute}` : `${minute}`));
        }
        else if (minHour === 12 && timeType === "PM") {
            disabledPmMinutes.push(...Array.from({ length: minMinute }, (_, minute) => minute <= 9 ? `0${minute}` : `${minute}`));
        }
        else if (minHour > 12 && Number(selectedHour) === minHour - 12) {
            disabledPmMinutes.push(...Array.from({ length: minMinute }, (_, minute) => minute <= 9 ? `0${minute}` : `${minute}`));
        }
        return {
            AM: disabledAmMinutes,
            PM: disabledPmMinutes,
        };
    };
    const disabledMinutes = getDisabledMinutes();
    useEffect(() => {
        if (timeDialActive) {
            const activatedDials = Array.from(document.getElementsByClassName("timePickerItem--activated"));
            activatedDials.map((element) => element.scrollIntoView());
        }
    }, [timeDialActive]);
    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 (200 > window.innerHeight - elemRect.y) {
                direction = "bottom";
                offsetY = window.innerHeight - elemRect.y + 8;
            }
            setDropdownPosition({
                y: offsetY,
                x: offsetX,
                direction,
            });
        }
    };
    const handleOpen = (open) => {
        calculateDropdownPosition();
        setTimeDialActive(open);
        setTimeDone(!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(() => {
        if (Number(selectedHour) !== hourValue ||
            Number(selectedMinute) !== minuteValue ||
            timeType !== selectedTime) {
            onTimePicked(`${selectedHour}:${selectedMinute}:${timeType}`);
        }
    }, [selectedHour, selectedMinute, timeType]);
    useEffect(() => {
        window.addEventListener("click", handleClickOutside);
        window.addEventListener("wheel", () => calculateDropdownPosition());
        return () => {
            window.addEventListener("click", handleClickOutside);
            window.removeEventListener("wheel", () => calculateDropdownPosition());
        };
    }, []);
    return (_jsxs("div", { className: "timePickerDropdown--Active", ref: mainRef, children: [_jsxs("button", { className: "timePickerDropdown-Button", onClick: () => {
                    setTimeDone(timeDialActive);
                    handleOpen(!timeDialActive);
                }, children: [_jsx("p", { children: alwaysShowTime || timeDone
                            ? `${Number(selectedHour) < 10 ? `0${selectedHour}` : selectedHour}:${Number(selectedMinute) < 10
                                ? `0${selectedMinute}`
                                : selectedMinute} ${timeType}`
                            : "Time" }), _jsx(GetSvgIcon, { iconType: "clock", iconSize: "16" })] }), timeDialActive &&
                !!rootElem.current &&
                createPortal(_jsxs("div", { className: `${timeDialActive ? "" : "timePicker-hideTimeDial"} timePicker-Container`, ref: dropdownRef, style: {
                        [dropdownPosition.direction]: dropdownPosition?.y,
                        left: dropdownPosition?.x,
                    }, children: [_jsxs("div", { className: "time-scroll-container", children: [_jsx("div", { id: "hour-list", className: "timePickerVerticalList-Container", children: hours.map((item) => {
                                        const isDisabled = disabledHours[timeType].includes(item);
                                        return (_jsx("div", { className: `timePickerVerticalList-Item ${Number(item) === Number(selectedHour)
                                                ? "timePickerItem--activated"
                                                : ""} ${isDisabled ? "timePickerItem--disabled" : ""}`, onClick: () => {
                                                if (isDisabled)
                                                    return;
                                                setSelectedHour(Number(item).toString());
                                            }, children: item }));
                                    }) }), _jsx("div", { id: "minutes-list", className: "timePickerVerticalList-Container", children: minutes.map((item) => {
                                        const isDisabled = disabledMinutes[timeType].includes(item);
                                        return (_jsx("div", { className: `timePickerVerticalList-Item ${Number(item) === Number(selectedMinute)
                                                ? "timePickerItem--activated"
                                                : ""} ${isDisabled ? "timePickerItem--disabled" : ""}`, onClick: () => {
                                                if (isDisabled)
                                                    return;
                                                setSelectedMinute(Number(item).toString());
                                            }, children: item }));
                                    }) }), _jsx("div", { className: "timePickerVerticalList-Container", children: amOrPm.map((item) => {
                                        const isDisabled = disabledHours[item].length === 12;
                                        return (_jsx("div", { className: `timePickerVerticalList-Item ${item === timeType ? "timePickerItem--activated" : ""} ${isDisabled ? "timePickerItem--disabled" : ""}`, onClick: () => {
                                                if (isDisabled)
                                                    return;
                                                setTimeType(item);
                                            }, children: item }));
                                    }) })] }), !!timezone && _jsx("div", { className: "timezone", children: timezone })] }), rootElem.current)] }));
};
export default TimePicker;
