'use strict';

var jsxRuntime = require('../../node_modules/.pnpm/react@18.2.0/node_modules/react/jsx-runtime.cjs');
var popover = require('../popover/popover.cjs');
var textfield = require('../textfield/textfield.cjs');
var calendar = require('./calendar.cjs');
var calendar_module = require('./calendar.module.css.cjs');
var React = require('react');
var reactIcons_esm = require('../../node_modules/.pnpm/@radix-ui_react-icons@1.3.0_react@18.2.0/node_modules/@radix-ui/react-icons/dist/react-icons.esm.cjs');
var dayjs_min = require('../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/dayjs.min.cjs');
var customParseFormat = require('../../node_modules/.pnpm/dayjs@1.11.11/node_modules/dayjs/plugin/customParseFormat.cjs');

dayjs_min.default.extend(customParseFormat.default);
function DatePicker({ side = "top", dateFormat = "DD/MM/YYYY", placeholder = "DD/MM/YYYY", textFieldProps, calendarProps, value = new Date(), onSelect = () => { }, children, }) {
    const [showCalendar, setShowCalendar] = React.useState(false);
    const [selectedDate, setSelectedDate] = React.useState(value);
    const [inputState, setInputState] = React.useState();
    const formattedDate = dayjs_min.default(selectedDate).format(dateFormat);
    const isDropdownOpenRef = React.useRef(false);
    const textFieldRef = React.useRef(null);
    const contentRef = React.useRef(null);
    const isInputFieldFocused = React.useRef(false);
    const selectedDateRef = React.useRef(selectedDate);
    React.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 = React.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_min.default(selectedDateRef.current).format(dateFormat);
        if (textFieldRef.current)
            textFieldRef.current.value = updatedVal;
        if (inputState === undefined)
            onSelect(dayjs_min.default(updatedVal).toDate());
        document.removeEventListener('mouseup', handleMouseDown);
    }
    const handleSelect = (day) => {
        setSelectedDate(day);
        onSelect(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_min.default(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_min.default(date).isSameOrAfter(calendarProps.startMonth) : true;
        const isBefore = calendarProps?.endMonth !== undefined ? dayjs_min.default(date).isSameOrBefore(calendarProps.endMonth) : true;
        const isValid = isValidDate && isAfter && isBefore && dayjs_min.default(date).isSameOrBefore(dayjs_min.default());
        if (isValid) {
            setSelectedDate(date.toDate());
            if (inputState === 'invalid')
                setInputState(undefined);
        }
        else {
            setInputState('invalid');
        }
    }
    const defaultTrigger = (jsxRuntime.jsxRuntimeExports.jsx(textfield.TextField, { ref: textFieldRef, defaultValue: formattedDate, trailing: jsxRuntime.jsxRuntimeExports.jsx(reactIcons_esm.CalendarIcon, {}), onChange: handleInputChange, onFocus: handleInputFocus, onBlur: handleInputBlur, state: inputState, placeholder: placeholder, onKeyUp: handleKeyUp, ...textFieldProps }));
    const trigger = typeof children === 'function'
        ? children({ selectedDate: formattedDate })
        : children || defaultTrigger;
    return (jsxRuntime.jsxRuntimeExports.jsxs(popover.Popover, { open: showCalendar, onOpenChange: onOpenChange, children: [jsxRuntime.jsxRuntimeExports.jsx(popover.Popover.Trigger, { asChild: true, children: trigger }), jsxRuntime.jsxRuntimeExports.jsx(popover.Popover.Content, { side: side, className: calendar_module.default.calendarPopover, ref: contentRef, children: jsxRuntime.jsxRuntimeExports.jsx(calendar.Calendar, { required: true, ...calendarProps, onDropdownOpen: onDropdownOpen, mode: "single", selected: selectedDate, month: selectedDate, onSelect: handleSelect, onMonthChange: setSelectedDate }) })] }));
}

exports.DatePicker = DatePicker;
//# sourceMappingURL=date-picker.cjs.map
