"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { CalendarIcon } from '../../node_modules/.pnpm/@radix-ui_react-icons@1.3.2_react@19.1.1/node_modules/@radix-ui/react-icons/dist/react-icons.esm.js';
import { cx } from '../../node_modules/.pnpm/class-variance-authority@0.7.1/node_modules/class-variance-authority/dist/index.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 { InputField } from '../input-field/input-field.js';
import { Popover } from '../popover/popover.js';
import { Calendar } from './calendar.js';
import styles from './calendar.module.css.js';

dayjs.extend(customParseFormat);
function DatePicker({ dateFormat = 'DD/MM/YYYY', inputFieldProps, calendarProps, value = new Date(), onSelect = () => { }, children, showCalendarIcon = true, timeZone, popoverProps }) {
    const [showCalendar, setShowCalendar] = useState(false);
    const [selectedDate, setSelectedDate] = useState(value);
    const [error, setError] = useState();
    const formattedDate = dayjs(selectedDate).format(dateFormat);
    const isDropdownOpenRef = useRef(false);
    const inputFieldRef = useRef(null);
    const contentRef = useRef(null);
    const isInputFieldFocused = useRef(false);
    const selectedDateRef = useRef(selectedDate);
    useEffect(() => {
        selectedDateRef.current = selectedDate;
    }, [selectedDate]);
    const isElementOutside = useCallback((el) => {
        return (!isDropdownOpenRef.current && // Month and Year dropdown from Date picker
            !inputFieldRef.current?.contains(el) && // InputField
            !contentRef.current?.contains(el));
    }, []);
    const handleMouseDown = useCallback((event) => {
        const el = event.target;
        if (el && isElementOutside(el))
            removeEventListeners();
    }, [isElementOutside]);
    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 (inputFieldRef.current)
            inputFieldRef.current.value = updatedVal;
        if (!error && !skipUpdate)
            onSelect(dayjs(updatedVal).toDate());
        document.removeEventListener('mouseup', handleMouseDown);
    }
    const handleSelect = (day) => {
        setSelectedDate(day);
        onSelect(day);
        setError(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(() => inputFieldRef.current?.select());
        }
    }
    function handleKeyUp(event) {
        if (event.code === 'Enter' && inputFieldRef.current) {
            inputFieldRef.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, 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());
            setError(undefined);
        }
        else {
            setError('Invalid date');
        }
    }
    const defaultTrigger = (jsx(InputField, { size: 'small', placeholder: 'Select date', error: error, className: styles.datePickerInput, trailingIcon: showCalendarIcon ? jsx(CalendarIcon, {}) : undefined, ...inputFieldProps, ref: inputFieldRef, defaultValue: formattedDate, onChange: handleInputChange, onFocus: handleInputFocus, onBlur: handleInputBlur, onKeyUp: handleKeyUp }));
    const trigger = typeof children === 'function' ? (children({ selectedDate: formattedDate })) : children ? (jsx("div", { children: children })) : (jsx("div", { children: defaultTrigger }));
    return (jsxs(Popover, { open: showCalendar, onOpenChange: onOpenChange, children: [jsx(Popover.Trigger, { asChild: true, children: trigger }), jsx(Popover.Content, { ref: contentRef, ...popoverProps, className: cx(styles.calendarPopover, popoverProps?.className), side: popoverProps?.side ?? 'top', children: jsx(Calendar, { required: true, ...calendarProps, timeZone: timeZone, onDropdownOpen: onDropdownOpen, mode: 'single', selected: selectedDate, month: selectedDate, onSelect: handleSelect, onMonthChange: setSelectedDate }) })] }));
}

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