"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = DateRangePicker;
const classnames_1 = __importDefault(require("classnames"));
const dayjs_1 = __importDefault(require("dayjs"));
const isSameOrAfter_1 = __importDefault(require("dayjs/plugin/isSameOrAfter"));
const isSameOrBefore_1 = __importDefault(require("dayjs/plugin/isSameOrBefore"));
const react_1 = __importStar(require("react"));
const DateRangePickerContext_1 = require("./DateRangePickerContext");
const DateRangePickerMonth_1 = __importDefault(require("./DateRangePickerMonth"));
const Icon_1 = __importStar(require("../Icon/Icon"));
const Color_1 = require("../../../util/Color");
const BookingWizard_1 = require("../BookingWizard/BookingWizard");
const DateRangePicker_module_scss_1 = __importDefault(require("./DateRangePicker.module.scss"));
dayjs_1.default.extend(isSameOrBefore_1.default);
dayjs_1.default.extend(isSameOrAfter_1.default);
var EDateRangePickingState;
(function (EDateRangePickingState) {
    EDateRangePickingState[EDateRangePickingState["StartDate"] = 1] = "StartDate";
    EDateRangePickingState[EDateRangePickingState["EndDate"] = 2] = "EndDate";
})(EDateRangePickingState || (EDateRangePickingState = {}));
function DateRangePicker(props) {
    var _a, _b;
    const { showYearOnCalendar, yearDisplayOption, showArrows = true, monthCount = 2 } = props;
    const [currentMonth, setCurrentMonth] = (0, react_1.useState)(props.selectedStartDate ? props.selectedStartDate : (0, dayjs_1.default)());
    const [selectedStartDate, setSelectedStartDate] = (0, react_1.useState)((_a = props.selectedStartDate) !== null && _a !== void 0 ? _a : (props.fixedStartDate ? (0, dayjs_1.default)() : null));
    const [selectedEndDate, setSelectedEndDate] = (0, react_1.useState)((_b = props.selectedEndDate) !== null && _b !== void 0 ? _b : null);
    const [hoveringOverDate, setHoveringOverDate] = (0, react_1.useState)(null);
    const [pickingState, setPickingState] = (0, react_1.useState)(props.fixedStartDate ? EDateRangePickingState.EndDate : EDateRangePickingState.StartDate);
    const onClickDate = (newDate) => __awaiter(this, void 0, void 0, function* () {
        let newPickingState = null;
        switch (pickingState) {
            default:
            case EDateRangePickingState.StartDate:
                newPickingState = EDateRangePickingState.EndDate;
                setSelectedStartDate(newDate);
                setSelectedEndDate(null);
                break;
            case EDateRangePickingState.EndDate:
                if (newDate.isBefore(selectedStartDate)) {
                    setSelectedStartDate(newDate);
                    newPickingState = EDateRangePickingState.EndDate;
                }
                else {
                    newPickingState = EDateRangePickingState.StartDate;
                    setHoveringOverDate(null);
                    const nextAvailableDay = newDate;
                    if (newDate.isSame(selectedStartDate)) {
                        setSelectedEndDate(nextAvailableDay.add(1, 'day'));
                    }
                    else {
                        setSelectedEndDate(nextAvailableDay);
                    }
                }
                break;
        }
        setPickingState(props.fixedStartDate ? EDateRangePickingState.EndDate : newPickingState);
    });
    const onHoveredOverDay = (day) => {
        if (selectedStartDate && !selectedEndDate) {
            setHoveringOverDate(day);
        }
    };
    const firstUpdate = (0, react_1.useRef)(null);
    (0, react_1.useEffect)(() => {
        if (firstUpdate.current) {
            firstUpdate.current = null;
            return;
        }
        if (props.onStartDateChanged) {
            props.onStartDateChanged(selectedStartDate);
        }
    }, [selectedStartDate]);
    (0, react_1.useLayoutEffect)(() => {
        if (firstUpdate.current) {
            firstUpdate.current = null;
            return;
        }
        if (props.onEndDateChanged) {
            props.onEndDateChanged(selectedEndDate);
        }
    }, [selectedEndDate]);
    const context = {
        today: (0, dayjs_1.default)(),
        todayInUnix: (0, dayjs_1.default)().unix(),
        startDate: selectedStartDate,
        endDate: selectedEndDate,
        hoveredMonth: hoveringOverDate,
        onHoverOver: onHoveredOverDay,
        currentMonth,
        onDayClicked: (date) => {
            onClickDate(date);
        },
        fixedStartDate: !!props.fixedStartDate,
        theme: props.theme,
    };
    const printMonths = (0, react_1.useMemo)(() => {
        const monthsToRender = props.showMultipleMonths ? Array.from({ length: monthCount }, (_, index) => currentMonth.clone().add(index, 'month')) : [currentMonth];
        return (react_1.default.createElement(react_1.default.Fragment, null, monthsToRender.map((month, index) => (react_1.default.createElement(DateRangePickerMonth_1.default, { key: index, small: props.small, showingMonth: month, showYearOnCalendar: showYearOnCalendar, yearDisplayOption: yearDisplayOption })))));
    }, [currentMonth, props.showMultipleMonths, props.small, props.theme, showYearOnCalendar, yearDisplayOption, monthCount]);
    const calendarClassNames = (0, classnames_1.default)(DateRangePicker_module_scss_1.default['roomstay-calendar'], props.className, {
        [DateRangePicker_module_scss_1.default['--small']]: props.small,
        [DateRangePicker_module_scss_1.default['--single']]: !props.showMultipleMonths,
        [DateRangePicker_module_scss_1.default['--specific']]: props.theme === BookingWizard_1.EBookingWizardTheme.Specific,
    });
    const previousMonthOnClick = () => {
        setCurrentMonth(currentMonth.subtract(1, 'month'));
    };
    const nextMonthOnClick = () => {
        setCurrentMonth(currentMonth.add(1, 'month'));
    };
    const iconSize = props.theme === BookingWizard_1.EBookingWizardTheme.Specific ? '16px' : '24px';
    const iconBackground = props.theme === BookingWizard_1.EBookingWizardTheme.Specific ? undefined : Color_1.Color.Snow;
    return (react_1.default.createElement(DateRangePickerContext_1.DateRangePickerContext.Provider, { value: context },
        react_1.default.createElement("div", { ref: firstUpdate, className: calendarClassNames },
            showArrows && (react_1.default.createElement("div", { className: DateRangePicker_module_scss_1.default['roomstay-calendar-navigation'] },
                react_1.default.createElement(Icon_1.default, { className: DateRangePicker_module_scss_1.default['roomstay-calendar-arrow'], icon: Icon_1.IconType.ArrowLeft2, onClick: previousMonthOnClick, color: Color_1.Color.Navy, backgroundColor: iconBackground, borderRadius: "round", size: iconSize }),
                react_1.default.createElement(Icon_1.default, { className: DateRangePicker_module_scss_1.default['roomstay-calendar-arrow'], icon: Icon_1.IconType.ArrowRight2, onClick: nextMonthOnClick, color: Color_1.Color.Navy, backgroundColor: iconBackground, borderRadius: "round", size: iconSize }))),
            printMonths)));
}
//# sourceMappingURL=DateRangePicker.js.map