"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.BWSearchButton = exports.BWClearButton = exports.BWPromoCodeSection = exports.BookingWizardContent = void 0;
require("react-spring-bottom-sheet/dist/style.css");
const contexts_1 = require("../../../contexts/index.js");
const ui_1 = require("@roomstay/ui");
const classnames_1 = __importDefault(require("classnames"));
const dayjs_1 = __importDefault(require("dayjs"));
const react_1 = __importStar(require("react"));
const react_i18next_1 = require("react-i18next");
const AvailabilityAPI_1 = __importDefault(require("../../../api/AvailabilityAPI"));
const RoomstayThemeEngine_1 = __importDefault(require("../../../providers/RoomstayThemeEngine"));
const Translation_1 = require("../../../translations/Translation");
const BEButton_1 = __importDefault(require("../BEButton"));
const BookingWizard_1 = require("./BookingWizard");
const BookingWizard_module_scss_1 = __importDefault(require("./BookingWizard.module.scss"));
const BookingWizardContext_1 = require("./BookingWizardContext");
const BookingWizardDateSelector_1 = require("./BookingWizardDateSelector/BookingWizardDateSelector");
const BookingWizardGuestSelector_1 = require("./BookingWizardGuestSelector/BookingWizardGuestSelector");
const BookingWizardHotelSelector_1 = require("./BookingWizardHotelSelector/BookingWizardHotelSelector");
const BookingWizardPromoCode_1 = require("./BookingWizardPromoCode/BookingWizardPromoCode");
const BookingWizardContent = ({ properties, selectedProperty: defaultProperty, defaultColors, classname, maxAdults, disableChild, showInfants, disableRoom, defaultValues, dateFormat, }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
    const bwContext = (0, react_1.useContext)(BookingWizardContext_1.BookingWizardContext);
    const beContext = (0, react_1.useContext)(contexts_1.BookingEngineContext);
    const { t } = (0, react_i18next_1.useTranslation)();
    const [checkInDate, setCheckInDate] = (0, react_1.useState)((defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.checkIn) ? (0, dayjs_1.default)(defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.checkIn) : (0, dayjs_1.default)());
    const [checkOutDate, setCheckOutDate] = (0, react_1.useState)((defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.checkout) ? (0, dayjs_1.default)(defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.checkout) : (0, dayjs_1.default)().add(1, 'days'));
    const [adults, setAdults] = (0, react_1.useState)((_b = (_a = defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.guests) === null || _a === void 0 ? void 0 : _a.adults) !== null && _b !== void 0 ? _b : 1);
    const [children, setChildren] = (0, react_1.useState)((_d = (_c = defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.guests) === null || _c === void 0 ? void 0 : _c.children) !== null && _d !== void 0 ? _d : 0);
    const [infants, setInfants] = (0, react_1.useState)((_f = (_e = defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.guests) === null || _e === void 0 ? void 0 : _e.infants) !== null && _f !== void 0 ? _f : 0);
    const [room, setRoom] = (0, react_1.useState)((_h = (_g = defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.guests) === null || _g === void 0 ? void 0 : _g.room) !== null && _h !== void 0 ? _h : 1);
    const [promoCode, setPromoCode] = (0, react_1.useState)((defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.promoCode) || '');
    const [promoCodeValid, setPromoCodeValid] = (0, react_1.useState)();
    const [selectedProperty, setSelectedProperty] = (0, react_1.useState)(defaultProperty);
    const [hotelContainerRef, setHotelContainerRef] = (0, react_1.useState)(null);
    const [guestsContainerRef, setGuestContainerRef] = (0, react_1.useState)(null);
    (0, react_1.useEffect)(() => {
        if (selectedProperty === null || selectedProperty === void 0 ? void 0 : selectedProperty.colors) {
            RoomstayThemeEngine_1.default.changeTheme(selectedProperty.colors);
        }
        else if (defaultColors) {
            RoomstayThemeEngine_1.default.changeTheme(defaultColors);
        }
    }, [selectedProperty]);
    const engineConfig = beContext.engine.getConfig();
    const guestAgeConfig = engineConfig.guestAgeConfig;
    const yearDisplayOption = (0, react_1.useMemo)(() => {
        var _a, _b;
        return (_b = (_a = selectedProperty === null || selectedProperty === void 0 ? void 0 : selectedProperty.yearDisplayOption) !== null && _a !== void 0 ? _a : engineConfig.yearDisplayOption) !== null && _b !== void 0 ? _b : '';
    }, [selectedProperty]);
    const showYearOnCalendar = (0, react_1.useMemo)(() => {
        var _a, _b;
        return !!((_b = (_a = selectedProperty === null || selectedProperty === void 0 ? void 0 : selectedProperty.showYearOnCalendar) !== null && _a !== void 0 ? _a : engineConfig.showYearOnCalendar) !== null && _b !== void 0 ? _b : '');
    }, [selectedProperty]);
    const setGuest = (guests) => {
        setAdults(guests.adults);
        setChildren(guests.children);
        setInfants(guests.infants);
        setRoom(guests.room);
    };
    const setDate = (startDate, endDate) => {
        setCheckInDate(startDate);
        setCheckOutDate(endDate);
    };
    const isValid = () => {
        const isPropertyHidden = bwContext.stateSections[BookingWizard_1.EBookingWizardSection.Property].hidden;
        const isGuestSelectHidden = bwContext.stateSections[BookingWizard_1.EBookingWizardSection.Guest].hidden;
        if (!isPropertyHidden && !selectedProperty)
            return false;
        if (!checkInDate)
            return false;
        if (!checkOutDate)
            return false;
        if (!isGuestSelectHidden && adults + children <= 0)
            return false;
        return true;
    };
    const _onSubmit = () => {
        var _a;
        if (!isValid())
            return false;
        // After passing validation, we pass the function up the chain for the engine
        // Implementor to decide where the user should be redirected to
        // This is to give the hotel team a chance to add tracking, or modify the request on their end.
        (_a = bwContext.onSubmit) === null || _a === void 0 ? void 0 : _a.call(bwContext, {
            id: selectedProperty === null || selectedProperty === void 0 ? void 0 : selectedProperty.id,
            checkIn: checkInDate,
            checkout: checkOutDate,
            promoCode,
            guests: {
                adults,
                children,
                infants,
                room,
            },
        });
    };
    const _onPromoCodeChange = (value) => __awaiter(void 0, void 0, void 0, function* () {
        setPromoCode === null || setPromoCode === void 0 ? void 0 : setPromoCode(value || '');
        if (!value) {
            setPromoCodeValid(undefined);
        }
        else if (isValid() && selectedProperty && (selectedProperty === null || selectedProperty === void 0 ? void 0 : selectedProperty.id) !== 'All' && checkInDate && checkOutDate) {
            const result = yield new AvailabilityAPI_1.default().fetchAvailability({
                fromDate: checkInDate,
                toDate: checkOutDate,
                adults,
                children,
                infants,
                promoCode: value,
                hotelId: selectedProperty === null || selectedProperty === void 0 ? void 0 : selectedProperty.id,
                promoOnly: true,
            });
            const rate = Object.values(result.ratePlans).find((rate) => rate.promoCode === value);
            setPromoCodeValid(!!rate);
        }
    });
    const submitButton = (react_1.default.createElement(BEButton_1.default, { disabled: !isValid(), className: BookingWizard_module_scss_1.default.bookNowBtn, onClick: _onSubmit }, t(Translation_1.Translation.Misc.BookNow)));
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { className: (0, classnames_1.default)(BookingWizard_module_scss_1.default.content, BookingWizard_module_scss_1.default[`--${bwContext.layout}`], {
                [BookingWizard_module_scss_1.default['--vertical']]: bwContext.layout === 'button',
                [BookingWizard_module_scss_1.default.inline]: bwContext.type === 'inline',
            }, classname) },
            react_1.default.createElement(BWPropertySelectorSection, { hidden: bwContext.stateSections[BookingWizard_1.EBookingWizardSection.Property].hidden, inactive: bwContext.stateSections[BookingWizard_1.EBookingWizardSection.Property].inactive, withLabel: !bwContext.isImagesThemeMobile, divider: !bwContext.isImagesThemeMobile, containerRef: hotelContainerRef, setContainerRef: setHotelContainerRef, properties: properties, selectedProperty: selectedProperty, setSelectedProperty: setSelectedProperty, classname: classname, t: t, searchConfig: engineConfig.searchConfig }),
            react_1.default.createElement(BookingWizardDateSelector_1.BookingWizardDateSelector, { hidden: bwContext.stateSections[BookingWizard_1.EBookingWizardSection.Date].hidden, inactive: bwContext.stateSections[BookingWizard_1.EBookingWizardSection.Date].inactive, onChange: setDate, defaultStartDate: checkInDate ? (0, dayjs_1.default)(checkInDate) : undefined, defaultEndDate: checkOutDate ? (0, dayjs_1.default)(checkOutDate) : undefined, dateFormat: dateFormat, showYearOnCalendar: showYearOnCalendar, yearDisplayOption: yearDisplayOption, notes: bwContext.isImagesTheme ? (_j = engineConfig === null || engineConfig === void 0 ? void 0 : engineConfig.notes) === null || _j === void 0 ? void 0 : _j.date : undefined }),
            react_1.default.createElement(BWGuestSelectorSection, { hidden: bwContext.stateSections[BookingWizard_1.EBookingWizardSection.Guest].hidden, inactive: bwContext.stateSections[BookingWizard_1.EBookingWizardSection.Guest].inactive, divider: !bwContext.isImagesThemeMobile, isImagesTheme: bwContext.isImagesTheme, containerRef: guestsContainerRef, setContainerRef: setGuestContainerRef, onChange: setGuest, maxAdults: maxAdults, disableChild: disableChild, showInfants: showInfants, disableRoom: disableRoom, config: guestAgeConfig, notes: bwContext.isImagesTheme ? (_k = engineConfig === null || engineConfig === void 0 ? void 0 : engineConfig.notes) === null || _k === void 0 ? void 0 : _k.guest : undefined, defaultValue: {
                    adults: adults,
                    children: children,
                    room: room,
                    infants: infants,
                }, defaultGuestConfig: {
                    adults: (_l = defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.guests) === null || _l === void 0 ? void 0 : _l.adults,
                    children: (_m = defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.guests) === null || _m === void 0 ? void 0 : _m.children,
                    room: (_o = defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.guests) === null || _o === void 0 ? void 0 : _o.room,
                    infants: (_p = defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues.guests) === null || _p === void 0 ? void 0 : _p.infants,
                }, promoCodeConfig: {
                    divider: false,
                    withLabel: true,
                    promoCode,
                    setPromoCode,
                    onChange: _onPromoCodeChange,
                    valid: promoCodeValid,
                    hideTooltip: engineConfig.hideTooltips,
                }, submitConfig: {
                    onSubmit: _onSubmit,
                    disabledNext: !isValid(),
                } }),
            react_1.default.createElement(exports.BWPromoCodeSection, { hidden: bwContext.stateSections[BookingWizard_1.EBookingWizardSection.Promo].hidden, inactive: bwContext.stateSections[BookingWizard_1.EBookingWizardSection.Promo].inactive, isImagesTheme: bwContext.isImagesTheme, setPromoCode: setPromoCode, promoCode: promoCode, onChange: _onPromoCodeChange, valid: promoCodeValid, hideTooltip: engineConfig.hideTooltips, t: t, divider: true, withLabel: true }),
            bwContext.layout !== 'horizontal-condensed' && !bwContext.isImagesThemeMobile && react_1.default.createElement(SubmitButtonSection, { button: submitButton })),
        bwContext.layout === 'horizontal-condensed' && !bwContext.isImagesThemeMobile && (react_1.default.createElement("div", { className: (0, classnames_1.default)(BookingWizard_module_scss_1.default.content, classname) },
            react_1.default.createElement("div", { className: (0, classnames_1.default)(BookingWizard_module_scss_1.default.action, BookingWizard_module_scss_1.default.centerItems, 'u-marg-top u-marg-top--light@l-') }, submitButton)))));
};
exports.BookingWizardContent = BookingWizardContent;
const BWPropertySelectorSection = ({ inactive, hidden, containerRef, setContainerRef, properties, selectedProperty, setSelectedProperty, classname, t, divider = true, withLabel = true, searchConfig, }) => {
    if (hidden)
        return null;
    const [focused, setFocused] = react_1.default.useState(false);
    const [searchQuery, setSearchQuery] = (0, react_1.useState)('');
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { ref: setContainerRef, className: (0, classnames_1.default)(BookingWizard_module_scss_1.default.item, BookingWizard_module_scss_1.default['item-hotel'], {
                [BookingWizard_module_scss_1.default['inactive']]: inactive,
            }) },
            react_1.default.createElement("div", { className: (0, classnames_1.default)(BookingWizard_module_scss_1.default['item-ellipsis-wrapper']), onFocus: () => setFocused(true), onBlur: () => setFocused(false) },
                withLabel && react_1.default.createElement("label", { className: BookingWizard_module_scss_1.default.label }, t(Translation_1.Translation.Misc.ChooseHotel)),
                react_1.default.createElement(BookingWizardHotelSelector_1.BookingWizardHotelSelector, { followElement: containerRef, onChange: (value) => {
                        setSelectedProperty(value || undefined);
                    }, properties: properties, selectedProperty: selectedProperty, contentClassName: (0, classnames_1.default)(classname), searchConfig: searchConfig
                        ? Object.assign(Object.assign({}, searchConfig), { searchQuery,
                            setSearchQuery,
                            focused }) : undefined }))),
        divider ? (react_1.default.createElement("div", { className: (0, classnames_1.default)(BookingWizard_module_scss_1.default.divider, {
                [BookingWizard_module_scss_1.default['inactive']]: inactive,
            }) })) : null));
};
const BWGuestSelectorSection = ({ inactive, hidden, containerRef, setContainerRef, defaultValue: _defaultValue, onChange, maxAdults, disableChild, showInfants, disableRoom, config, notes, defaultGuestConfig, divider, promoCodeConfig, submitConfig, isImagesTheme, }) => {
    if (hidden)
        return null;
    const { t } = (0, react_i18next_1.useTranslation)();
    const [isOverlayOpen, setIsOverlayOpen] = (0, react_1.useState)(false);
    const [defaultValue, setDefaultValue] = (0, react_1.useState)(_defaultValue);
    const onOverlayOpenChange = (isOpen) => {
        setIsOverlayOpen(isOpen);
    };
    const onClearHandler = () => {
        const emptyValues = {
            adults: 0,
            children: 0,
            room: 0,
            infants: 0,
        };
        onChange(Object.assign({}, emptyValues));
        setDefaultValue(Object.assign({}, emptyValues));
    };
    return (react_1.default.createElement(react_1.default.Fragment, null,
        divider ? (react_1.default.createElement("div", { className: (0, classnames_1.default)(BookingWizard_module_scss_1.default.divider, {
                [BookingWizard_module_scss_1.default['inactive']]: inactive,
            }) })) : null,
        react_1.default.createElement("div", { ref: setContainerRef, className: (0, classnames_1.default)(BookingWizard_module_scss_1.default.item, {
                [BookingWizard_module_scss_1.default['inactive']]: inactive,
            }) },
            react_1.default.createElement("div", { className: BookingWizard_module_scss_1.default['item-with-icon'] },
                react_1.default.createElement("div", { className: (0, classnames_1.default)(BookingWizard_module_scss_1.default['item-fullwidth'], BookingWizard_module_scss_1.default['item-ellipsis-wrapper']) },
                    react_1.default.createElement("label", { className: BookingWizard_module_scss_1.default.label }, t(Translation_1.Translation.Misc.Guests)),
                    react_1.default.createElement(BookingWizardGuestSelector_1.BookingWizardGuestSelector, Object.assign({ defaultValue: defaultValue, onChange: onChange, maxAdults: maxAdults, disableChild: disableChild, showInfants: showInfants, disableRoom: disableRoom, followElement: containerRef }, config, { notes: isImagesTheme ? notes : undefined, onOverlayOpenChange: onOverlayOpenChange, promoCodeConfig: promoCodeConfig, submitConfig: submitConfig }))),
                isImagesTheme && react_1.default.createElement(exports.BWClearButton, { show: isOverlayOpen, onClick: onClearHandler })))));
};
const BWPromoCodeSection = ({ inactive, hidden, setPromoCode, promoCode, onChange, valid, hideTooltip, t, isImagesTheme, divider = true, withLabel = true, }) => {
    if (hidden)
        return null;
    const onClearHandler = (event) => {
        setPromoCode('');
        event.preventDefault();
        event.stopPropagation();
    };
    const [focused, setFocused] = react_1.default.useState(false);
    return (react_1.default.createElement(react_1.default.Fragment, null,
        divider ? (react_1.default.createElement("div", { className: (0, classnames_1.default)(BookingWizard_module_scss_1.default.divider, {
                [BookingWizard_module_scss_1.default['inactive']]: inactive,
            }) })) : null,
        react_1.default.createElement("div", { className: (0, classnames_1.default)(BookingWizard_module_scss_1.default.item, BookingWizard_module_scss_1.default['item-promo-code-wrapper'], {
                [BookingWizard_module_scss_1.default['inactive']]: inactive,
            }), onFocus: () => setFocused(true), onBlur: () => setFocused(false) },
            react_1.default.createElement("div", { className: BookingWizard_module_scss_1.default['item-with-icon'] },
                react_1.default.createElement("div", { className: (0, classnames_1.default)(BookingWizard_module_scss_1.default['item-fullwidth'], BookingWizard_module_scss_1.default['item-ellipsis-wrapper']) },
                    withLabel && react_1.default.createElement("label", { className: BookingWizard_module_scss_1.default.label }, t(Translation_1.Translation.Misc.Promocode)),
                    react_1.default.createElement(BookingWizardPromoCode_1.BookingWizardPromoCode, { promoCode: promoCode, onChange: onChange, valid: valid, hideTooltip: hideTooltip })),
                isImagesTheme && react_1.default.createElement(exports.BWClearButton, { show: focused, onClick: onClearHandler })))));
};
exports.BWPromoCodeSection = BWPromoCodeSection;
const SubmitButtonSection = ({ button }) => react_1.default.createElement("div", { className: BookingWizard_module_scss_1.default.action }, button);
const BWIconButton = ({ show, onClick, hasLabel = false, bottomSheet = false, hasSearchInput = false, icon, name, className }) => {
    if (!show)
        return null;
    return (react_1.default.createElement("div", { onMouseDown: (e) => e.preventDefault(), onClick: onClick, className: (0, classnames_1.default)(className, {
            [BookingWizard_module_scss_1.default['--has-label']]: hasLabel,
            [BookingWizard_module_scss_1.default['--bottom-sheet']]: bottomSheet,
            [BookingWizard_module_scss_1.default['--has-search-input']]: hasSearchInput,
        }) },
        react_1.default.createElement(ui_1.Icon, { icon: icon, name: name })));
};
const BWClearButton = (props) => (react_1.default.createElement(BWIconButton, Object.assign({}, props, { icon: ui_1.IconType.Close, name: "Clear", className: BookingWizard_module_scss_1.default['clear-button'] })));
exports.BWClearButton = BWClearButton;
const BWSearchButton = (props) => (react_1.default.createElement(BWIconButton, Object.assign({}, props, { icon: ui_1.IconType.Search, name: "Search", className: BookingWizard_module_scss_1.default['search-button'] })));
exports.BWSearchButton = BWSearchButton;
//# sourceMappingURL=BookingWizardContent.js.map