import dayjs, {Dayjs} from 'dayjs'
import {RangePickerProps} from '../inner-comps/inner-range-picker'

export function syncDisplayedDatePair(
    mode: RangePickerProps['mode'],
    startValue: dayjs.Dayjs | null,
    endValue: dayjs.Dayjs | null,
    getDefaultDisplayDateRange?: (
        today: Dayjs,
    ) => {
        start: Dayjs
        end: Dayjs
    }
) {
    let startDisplayedDate: Dayjs
    let endDisplayedDate: Dayjs
    mode = mode || 'date'
    const startUnit = mode === 'date' ? 'month' : 'year'

    if ((startValue || endValue) || !getDefaultDisplayDateRange) {
        if (startValue && endValue) {
            startDisplayedDate = startValue.startOf(startUnit)
            endDisplayedDate = endValue.startOf(startUnit)
        } else if (!startValue && endValue) {
            endDisplayedDate = endValue.startOf(startUnit)
            startDisplayedDate = endDisplayedDate.subtract(1, startUnit)
        } else {
            startDisplayedDate = (startValue || dayjs()).startOf(startUnit)
            endDisplayedDate = startDisplayedDate.add(1, startUnit)
        }
    } else {
        const {start, end} = getDefaultDisplayDateRange(dayjs())
        startDisplayedDate = start
        endDisplayedDate = end
    }

    if (endDisplayedDate.isSame(startDisplayedDate)) {
        endDisplayedDate = endDisplayedDate.add(1, startUnit)
    }
    return {startDisplayedDate, endDisplayedDate}
}
