import React, { useMemo, useState, useCallback, useEffect } from "react";
import { getSortedValues, isValueUpdate } from "../utils";
/**
 * HOC для календаря, дающий возможность выбора диапазона даты
 */ export const withRange = (Component)=>({ value, min, max, disabledList, eventList, eventMonthList, disabledMonthList, eventYearList, disabledYearList, onChangeValue, onChangeStartOfRange, onChangeSingleValue, ...rest })=>{
        const [startExternalValue, endExternalValue] = useMemo(()=>value, [
            value
        ]);
        const [[startValue, endValue], setValues] = useState([
            startExternalValue,
            endExternalValue
        ]);
        const [prevValue, setPrevValue] = useState(value);
        if (isValueUpdate(value, prevValue)) {
            setValues([
                startExternalValue,
                endExternalValue
            ]);
            setPrevValue(value);
        }
        const handleOnChangeDay = useCallback((newDay, dateInfo)=>{
            if (endValue) {
                setValues([
                    newDay,
                    undefined
                ]);
                onChangeStartOfRange?.(newDay, dateInfo);
                return;
            }
            if (startValue) {
                setValues([
                    startValue,
                    newDay
                ]);
                const [first, second] = getSortedValues([
                    startValue,
                    newDay
                ]);
                onChangeValue([
                    first,
                    second
                ], dateInfo);
            } else {
                setValues([
                    newDay,
                    undefined
                ]);
                onChangeSingleValue?.(newDay, dateInfo);
            }
        }, [
            onChangeValue,
            onChangeStartOfRange,
            onChangeSingleValue,
            startValue,
            endValue
        ]);
        useEffect(()=>{
            setValues(value);
        }, [
            value[0],
            value[1]
        ]);
        return /*#__PURE__*/ React.createElement(Component, {
            value: [
                startValue,
                endValue
            ],
            onChangeValue: handleOnChangeDay,
            disabledList: disabledList,
            eventList: eventList,
            eventMonthList: eventMonthList,
            disabledMonthList: disabledMonthList,
            eventYearList: eventYearList,
            disabledYearList: disabledYearList,
            min: min,
            max: max,
            ...rest
        });
    };
