"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useBaseRangeDates = void 0;
const addMonths_1 = require("@astral/utils/date/addMonths");
const react_1 = require("react");
const hooks_1 = require("../../../../DatePicker/hooks");
/**
 * Хук возвращает базовые даты, по которым должны рендериться тот или иной месяц в календарях DateRangePicker
 */
const useBaseRangeDates = ({ minDate, maxDate, shouldReturnPrevValues, selectedStartDate, selectedEndDate, monthOffset = 1, }) => {
    const [startBaseDate, setStartBaseDate] = (0, react_1.useState)();
    const [endBaseDate, setEndBaseDate] = (0, react_1.useState)();
    const startBaseInitial = (0, react_1.useMemo)(() => {
        if (!selectedStartDate && selectedEndDate) {
            return (0, addMonths_1.addMonths)(selectedEndDate, -monthOffset);
        }
        return selectedStartDate;
    }, [monthOffset, selectedEndDate, selectedStartDate]);
    const endBaseInitial = (0, react_1.useMemo)(() => {
        if (!selectedStartDate && selectedEndDate) {
            return selectedEndDate;
        }
        return (0, addMonths_1.addMonths)(selectedStartDate || new Date(), monthOffset);
    }, [monthOffset, selectedEndDate, selectedStartDate]);
    const startBaseDateCandidate = (0, hooks_1.useBaseDateInRange)({
        minDate,
        maxDate,
        initialDate: startBaseInitial,
    });
    const endBaseDateCandidate = (0, hooks_1.useBaseDateInRange)({
        minDate,
        maxDate,
        initialDate: endBaseInitial,
    });
    (0, react_1.useEffect)(() => {
        if (!shouldReturnPrevValues) {
            setStartBaseDate(startBaseDateCandidate);
            setEndBaseDate(endBaseDateCandidate);
        }
        if (selectedStartDate) {
            setStartBaseDate(selectedStartDate);
        }
        if (selectedEndDate) {
            setEndBaseDate(selectedEndDate);
        }
    }, [
        endBaseDateCandidate,
        selectedEndDate,
        selectedStartDate,
        shouldReturnPrevValues,
        startBaseDateCandidate,
    ]);
    return {
        startBaseDate: startBaseDate || startBaseDateCandidate,
        endBaseDate: endBaseDate || endBaseDateCandidate,
    };
};
exports.useBaseRangeDates = useBaseRangeDates;
