import { j as jsxRuntimeExports } from '../../node_modules/.pnpm/react@18.2.0/node_modules/react/jsx-runtime.js';
import { CalendarIcon } from '../../node_modules/.pnpm/@radix-ui_react-icons@1.3.0_react@18.2.0/node_modules/@radix-ui/react-icons/dist/react-icons.esm.js';
import dayjs from '../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.js';
import customParseFormat from '../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/plugin/customParseFormat.js';
import { useState, useRef, useEffect, useCallback } from 'react';
import { Popover } from '../popover/popover.js';
import { TextField } from '../textfield/textfield.js';
import { Calendar } from './calendar.js';
import styles from './calendar.module.css.js';

dayjs.extend(customParseFormat);
function DatePicker({ side = "top", dateFormat = "DD/MM/YYYY", placeholder = "DD/MM/YYYY", textFieldProps, calendarProps, value = new Date(), onSelect = () => { }, children, showCalendarIcon = true, }) {
    const [showCalendar, setShowCalendar] = useState(false);
    const [selectedDate, setSelectedDate] = useState(value);
    const [inputState, setInputState] = useState();
    const formattedDate = dayjs(selectedDate).format(dateFormat);
    const isDropdownOpenRef = useRef(false);
    const textFieldRef = useRef(null);
    const contentRef = useRef(null);
    const isInputFieldFocused = useRef(false);
    const selectedDateRef = useRef(selectedDate);
    useEffect(() => {
        selectedDateRef.current = selectedDate;
    }, [selectedDate]);
    function isElementOutside(el) {
        return (!isDropdownOpenRef.current && // Month and Year dropdown from Date picker
            !textFieldRef.current?.contains(el) && // TextField
            !contentRef.current?.contains(el));
    }
    const handleMouseDown = useCallback((event) => {
        const el = event.target;
        if (el && isElementOutside(el))
            removeEventListeners();
    }, []);
    function registerEventListeners() {
        isInputFieldFocused.current = true;
        document.addEventListener("mouseup", handleMouseDown);
    }
    function removeEventListeners(skipUpdate = false) {
        isInputFieldFocused.current = false;
        setShowCalendar(false);
        const updatedVal = dayjs(selectedDateRef.current).format(dateFormat);
        if (textFieldRef.current)
            textFieldRef.current.value = updatedVal;
        if (inputState === undefined && !skipUpdate)
            onSelect(dayjs(updatedVal).toDate());
        document.removeEventListener("mouseup", handleMouseDown);
    }
    const handleSelect = (day) => {
        setSelectedDate(day);
        onSelect(day);
        setInputState(undefined);
        removeEventListeners(true);
    };
    function onDropdownOpen() {
        isDropdownOpenRef.current = true;
    }
    function onOpenChange(open) {
        if (!isDropdownOpenRef.current &&
            !(isInputFieldFocused.current && showCalendar)) {
            setShowCalendar(Boolean(open));
        }
        isDropdownOpenRef.current = false;
    }
    function handleInputFocus() {
        if (isInputFieldFocused.current)
            return;
        if (!showCalendar)
            setShowCalendar(true);
    }
    function handleInputBlur(event) {
        if (isInputFieldFocused.current) {
            const el = event.relatedTarget;
            if (el && isElementOutside(el))
                removeEventListeners();
        }
        else {
            registerEventListeners();
            setTimeout(() => textFieldRef.current?.select());
        }
    }
    function handleKeyUp(event) {
        if (event.code === "Enter" && textFieldRef.current) {
            textFieldRef.current.blur();
            removeEventListeners();
        }
    }
    function handleInputChange(event) {
        const { value } = event.target;
        const format = value.includes("/")
            ? "DD/MM/YYYY"
            : value.includes("-")
                ? "DD-MM-YYYY"
                : undefined;
        const date = dayjs(value.replace(/(\d{1,2})\/(\d{1,2})\/(\d{4})/, (_, day, month, year) => {
            return `${day.padStart(2, "0")}/${month.padStart(2, "0")}/${year}`; // Replaces [8/8/2024] to [08/08/2024]
        }), format);
        const isValidDate = date.isValid();
        const isAfter = calendarProps?.startMonth !== undefined
            ? dayjs(date).isSameOrAfter(calendarProps.startMonth)
            : true;
        const isBefore = calendarProps?.endMonth !== undefined
            ? dayjs(date).isSameOrBefore(calendarProps.endMonth)
            : true;
        const isValid = isValidDate && isAfter && isBefore && dayjs(date).isSameOrBefore(dayjs());
        if (isValid) {
            setSelectedDate(date.toDate());
            if (inputState === "invalid")
                setInputState(undefined);
        }
        else {
            setInputState("invalid");
        }
    }
    const defaultTrigger = (jsxRuntimeExports.jsx(TextField, { ref: textFieldRef, defaultValue: formattedDate, trailing: showCalendarIcon ? jsxRuntimeExports.jsx(CalendarIcon, {}) : undefined, onChange: handleInputChange, onFocus: handleInputFocus, onBlur: handleInputBlur, state: inputState, placeholder: placeholder, onKeyUp: handleKeyUp, className: styles.datePickerInput, ...textFieldProps }));
    const trigger = typeof children === "function"
        ? children({ selectedDate: formattedDate })
        : children || defaultTrigger;
    return (jsxRuntimeExports.jsxs(Popover, { open: showCalendar, onOpenChange: onOpenChange, children: [jsxRuntimeExports.jsx(Popover.Trigger, { asChild: true, children: trigger }), jsxRuntimeExports.jsx(Popover.Content, { side: side, className: styles.calendarPopover, ref: contentRef, children: jsxRuntimeExports.jsx(Calendar, { required: true, ...calendarProps, onDropdownOpen: onDropdownOpen, mode: "single", selected: selectedDate, month: selectedDate, onSelect: handleSelect, onMonthChange: setSelectedDate }) })] }));
}

export { DatePicker };
//# sourceMappingURL=date-picker.js.map
