import { j as jsxRuntimeExports } from '../node_modules/.pnpm/react@18.2.0/node_modules/react/jsx-runtime.js';
import { Popover } from '../popover/popover.js';
import { TextField } from '../textfield/textfield.js';
import { Calendar } from './calendar.js';
import styles from './calendar.module.css.js';
import { useState, useRef, useEffect, useCallback } from 'react';
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';

dayjs.extend(customParseFormat);
function DatePicker({ side = "top", dateFormat = "DD/MM/YYYY", placeholder = "DD/MM/YYYY", textFieldProps, calendarProps, value = new Date(), onSelect = () => { }, }) {
    const defaultDate = dayjs(value).format(dateFormat);
    const [showCalendar, setShowCalendar] = useState(false);
    const [calendarVal, setCalendarVal] = useState(value);
    const [inputState, setInputState] = useState();
    const isDropdownOpenRef = useRef(false);
    const textFieldRef = useRef(null);
    const contentRef = useRef(null);
    const isInputFieldFocused = useRef(false);
    const calendarValRef = useRef(value);
    useEffect(() => {
        calendarValRef.current = calendarVal;
    }, [calendarVal]);
    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() {
        isInputFieldFocused.current = false;
        setShowCalendar(false);
        const updatedVal = dayjs(calendarValRef.current).format(dateFormat);
        if (textFieldRef.current)
            textFieldRef.current.value = updatedVal;
        if (inputState === undefined)
            onSelect(dayjs(updatedVal).toDate());
        document.removeEventListener('mouseup', handleMouseDown);
    }
    const handleSelect = (day) => {
        onSelect(day);
        setCalendarVal(day);
        calendarValRef.current = day;
        setInputState(undefined);
        removeEventListeners();
    };
    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) {
            setCalendarVal(date.toDate());
            if (inputState === 'invalid')
                setInputState(undefined);
        }
        else {
            setInputState('invalid');
        }
    }
    return (jsxRuntimeExports.jsxs(Popover, { open: showCalendar, onOpenChange: onOpenChange, children: [jsxRuntimeExports.jsx(TextField, { ref: textFieldRef, defaultValue: defaultDate, trailing: jsxRuntimeExports.jsx(Popover.Trigger, { asChild: true, children: jsxRuntimeExports.jsx(CalendarIcon, {}) }), onChange: handleInputChange, onFocus: handleInputFocus, onBlur: handleInputBlur, state: inputState, placeholder: placeholder, onKeyUp: handleKeyUp, ...textFieldProps }), jsxRuntimeExports.jsx(Popover.Content, { side: side, className: styles.calendarPopover, ref: contentRef, children: jsxRuntimeExports.jsx(Calendar, { required: true, ...calendarProps, onDropdownOpen: onDropdownOpen, mode: "single", selected: calendarVal, month: calendarVal, onSelect: handleSelect, onMonthChange: setCalendarVal }) })] }));
}

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