import { isBefore, isSameDay } from "date-fns";
/**
 * In the case where we have:
 * - Mode: "range"
 * - selected: { from: undefined, to: Date } or
 * - selected: { from: Date, to: undefined }
 *
 *
 * RDP returns undefined for newSelection. We need to manually handle these cases.
 */
function pickRangeSelection({ newSelection, currentSelection: selected, newDate, caller, }) {
    const skip = !(selected === null || selected === void 0 ? void 0 : selected.from) || !(selected === null || selected === void 0 ? void 0 : selected.to) || !caller;
    if (caller === "from" && !skip) {
        const to = selected === null || selected === void 0 ? void 0 : selected.to;
        if (!to) {
            return { from: newDate, to: undefined };
        }
        if (isSameDay(newDate, to)) {
            return { from: newDate, to: newDate };
        }
        if (isBefore(newDate, to)) {
            return { from: newDate, to };
        }
        /* newDate is after to — invalid range, clear to */
        return { from: newDate, to: undefined };
    }
    if (caller === "to" && !skip) {
        const from = selected === null || selected === void 0 ? void 0 : selected.from;
        if (!from) {
            return { from: newDate, to: undefined };
        }
        if (isSameDay(newDate, from)) {
            return { from: newDate, to: newDate };
        }
        if (isBefore(from, newDate)) {
            return { from, to: newDate };
        }
        /* newDate is before from — start fresh with newDate as the new from */
        return { from: newDate, to: undefined };
    }
    if (newSelection) {
        return newSelection;
    }
    // No caller - edge-case handling
    if (!(selected === null || selected === void 0 ? void 0 : selected.to)) {
        /**
         * If defaultSelected.from is defined, but not "to", and user selects the same date as "from",
         * we interpret this as user wanting to select a single date range (from === to).
         */
        if ((selected === null || selected === void 0 ? void 0 : selected.from) && isSameDay(selected.from, newDate)) {
            return { from: newDate, to: newDate };
        }
        return { from: newDate, to: undefined };
    }
    let range;
    if (isSameDay(selected.to, newDate)) {
        range = undefined;
    }
    else if (isBefore(newDate, selected.to)) {
        range = { from: newDate, to: selected.to };
    }
    else {
        range = { from: selected.to, to: newDate };
    }
    return range;
}
export { pickRangeSelection };
//# sourceMappingURL=pick-range-selection.js.map