import { addMonths } from '@astral/utils/date/addMonths';
import { useEffect, useMemo, useState } from 'react';
import { useBaseDateInRange } from '../../../../DatePicker/hooks';
/**
 * Хук возвращает базовые даты, по которым должны рендериться тот или иной месяц в календарях DateRangePicker
 */
export const useBaseRangeDates = ({ minDate, maxDate, shouldReturnPrevValues, selectedStartDate, selectedEndDate, monthOffset = 1, }) => {
    const [startBaseDate, setStartBaseDate] = useState();
    const [endBaseDate, setEndBaseDate] = useState();
    const startBaseInitial = useMemo(() => {
        if (!selectedStartDate && selectedEndDate) {
            return addMonths(selectedEndDate, -monthOffset);
        }
        return selectedStartDate;
    }, [monthOffset, selectedEndDate, selectedStartDate]);
    const endBaseInitial = useMemo(() => {
        if (!selectedStartDate && selectedEndDate) {
            return selectedEndDate;
        }
        return addMonths(selectedStartDate || new Date(), monthOffset);
    }, [monthOffset, selectedEndDate, selectedStartDate]);
    const startBaseDateCandidate = useBaseDateInRange({
        minDate,
        maxDate,
        initialDate: startBaseInitial,
    });
    const endBaseDateCandidate = useBaseDateInRange({
        minDate,
        maxDate,
        initialDate: endBaseInitial,
    });
    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,
    };
};
