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 } 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 { Flex } from '../flex/flex.js';

function RangePicker({ side = "top", dateFormat = "DD/MM/YYYY", textFieldProps, calendarProps, onSelect = () => { }, value = {
    to: new Date(),
    from: new Date(),
}, pickerGroupClassName, }) {
    const [showCalendar, setShowCalendar] = useState(false);
    const [currentRangeField, setCurrentRangeField] = useState("from");
    const startDate = dayjs(value.from).format(dateFormat);
    const endDate = dayjs(value.to).format(dateFormat);
    // 1st click will select the start date.
    // 2nd click will select the end date.
    // 3rd click will select the start date again.
    const handleSelect = (range, selectedDay) => {
        const from = value?.from || range?.from;
        if (currentRangeField === "to" && dayjs(selectedDay).isAfter(dayjs(from))) {
            // update the end date
            onSelect({ from, to: selectedDay });
            setCurrentRangeField("from");
        }
        else {
            // reset the range and select start day
            onSelect({ from: selectedDay });
            setCurrentRangeField("to");
        }
    };
    function onOpenChange(open) {
        setShowCalendar(Boolean(open));
    }
    return (jsxRuntimeExports.jsxs(Popover, { open: showCalendar, onOpenChange: onOpenChange, children: [jsxRuntimeExports.jsx(Popover.Trigger, { asChild: true, children: jsxRuntimeExports.jsxs(Flex, { gap: "medium", className: pickerGroupClassName, children: [jsxRuntimeExports.jsx(TextField, { value: startDate, trailing: jsxRuntimeExports.jsx(CalendarIcon, {}), className: styles.datePickerInput, readOnly: true, ...textFieldProps }), jsxRuntimeExports.jsx(TextField, { value: endDate, trailing: jsxRuntimeExports.jsx(CalendarIcon, {}), className: styles.datePickerInput, readOnly: true, ...textFieldProps })] }) }), jsxRuntimeExports.jsx(Popover.Content, { side: side, className: styles.calendarPopover, children: jsxRuntimeExports.jsx(Calendar, { showOutsideDays: false, numberOfMonths: 2, defaultMonth: value.from, required: true, ...calendarProps, mode: "range", selected: value, onSelect: handleSelect }) })] }));
}

export { RangePicker };
//# sourceMappingURL=range-picker.js.map
