import { useState, useMemo, useEffect } from 'react';
import { parseDateRange } from '../utils/index';
import { addMonths } from 'date-fns';
var initDate = [new Date(), new Date()];
function createDateRangeWithSingleDate(dates, addMonthNum) {
    var startDate = dates[0], endDate = dates[1];
    var getStartFromEnd = function () {
        return endDate ? addMonths(endDate, -addMonthNum) : initDate[0];
    };
    var getEndFromStart = function () {
        return startDate ? addMonths(startDate, addMonthNum) : initDate[1];
    };
    return [startDate !== null && startDate !== void 0 ? startDate : getStartFromEnd(), endDate !== null && endDate !== void 0 ? endDate : getEndFromStart()];
}
export default function useRangeMergedProps(_a) {
    var value = _a.value, format = _a.format, defaultDate = _a.defaultDate, _b = _a.addMonthNum, addMonthNum = _b === void 0 ? 0 : _b;
    var _c = useState(initDate), defaultPanelDate = _c[0], setDefaultPanelDate = _c[1];
    var parseValue = useMemo(function () { return (value ? parseDateRange(value, format) : [null, null]); }, [value, format]);
    var _d = useState(parseValue), selected = _d[0], setSelected = _d[1];
    useEffect(function () {
        setSelected(parseValue);
    }, [parseValue]);
    useEffect(function () {
        var initDateRange = initDate;
        if ((selected === null || selected === void 0 ? void 0 : selected[0]) || (selected === null || selected === void 0 ? void 0 : selected[1])) {
            initDateRange = createDateRangeWithSingleDate(selected, addMonthNum);
        }
        else if ((defaultDate === null || defaultDate === void 0 ? void 0 : defaultDate[0]) && (defaultDate === null || defaultDate === void 0 ? void 0 : defaultDate[1])) {
            initDateRange = parseDateRange(defaultDate, format);
        }
        setDefaultPanelDate(initDateRange);
    }, [defaultDate, selected, format, addMonthNum]);
    return {
        selected: selected,
        parseValue: parseValue,
        setSelected: setSelected,
        defaultPanelDate: defaultPanelDate,
        setDefaultPanelDate: setDefaultPanelDate,
    };
}
