"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.AccountReservationSinglePage = void 0;
const contexts_1 = require("../../../contexts/index.js");
const core_1 = require("@roomstay/core");
const react_1 = __importStar(require("react"));
const react_i18next_1 = require("react-i18next");
const react_router_dom_1 = require("react-router-dom");
const Translation_1 = require("translations/Translation");
const BookingAPI_1 = __importDefault(require("../../../api/BookingAPI"));
const BEButton_1 = __importDefault(require("../../../components/generic/BEButton"));
const Card_1 = require("../../../components/generic/Card/Card/Card");
const Currency_1 = __importDefault(require("../../../components/generic/Currency"));
const GroupedCheckInOutTimes_1 = require("../../../components/generic/GroupedCheckInOutTimes/GroupedCheckInOutTimes");
const Headline_1 = __importDefault(require("../../../components/generic/Headline"));
const Icon_1 = require("../../../components/generic/Icon/Icon");
const IconText_1 = __importDefault(require("../../../components/generic/IconText/IconText"));
const LineBreak_1 = __importDefault(require("../../../components/generic/LineBreak"));
const SimpleModal_1 = __importStar(require("../../../components/generic/modal/SimpleModal"));
const Pill_1 = __importStar(require("../../../components/generic/Pill"));
const PrintOnly_1 = __importDefault(require("../../../components/generic/print/PrintOnly"));
const Text_1 = __importStar(require("../../../components/generic/Text"));
const ReservationItem_1 = require("../../../components/reservation/ReservationItem");
const ReservationList_1 = __importDefault(require("../../../components/reservation/ReservationList"));
const hooks_1 = require("../../../hooks");
const LoggedInUserHook_1 = require("../../../hooks/LoggedInUserHook");
const ModifyBookingFeature_1 = __importDefault(require("../../../providers/feature/ModifyBookingFeature"));
const Color_1 = require("../../../util/Color");
const DataLayer_1 = __importDefault(require("../../../util/DataLayer"));
const ScreenSize_1 = __importDefault(require("../../../util/ScreenSize"));
const StringHelper_1 = __importDefault(require("../../../util/StringHelper"));
const AccountRoutes_1 = require("../AccountRoutes");
const getRoomNamesString = (itineraries) => {
    var _a;
    const roomNames = {};
    for (const itinerary of itineraries) {
        roomNames[itinerary.roomName] = ((_a = roomNames[itinerary.roomName]) !== null && _a !== void 0 ? _a : 0) + 1;
    }
    return Object.keys(roomNames)
        .map((name) => {
        const numOfRooms = roomNames[name];
        if (numOfRooms <= 1)
            return `${name}`;
    })
        .join(' + ');
};
const CancelReservationModal = (props) => {
    const { items, booking, visible, onClose } = props;
    const { fetchRoomstayMember } = (0, react_1.useContext)(contexts_1.RoomstayMemberContext);
    const { t } = (0, react_i18next_1.useTranslation)();
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const onCancelClick = () => {
        setIsLoading(true);
        const cancellations = items.map((item) => BookingAPI_1.default.Reservation.cancelReservation(item.id, item.profile.email, booking.hotelId)
            .then(() => {
            DataLayer_1.default.instance.sendCancellationByReservationNumber(item.id);
        })
            .catch((error) => {
            contexts_1.ErrorHandler.add({
                title: t(Translation_1.Translation.Step.Thanks.Errors.CancelFailed),
                message: error.Message,
            });
        }));
        Promise.all(cancellations)
            .then(() => {
            fetchRoomstayMember === null || fetchRoomstayMember === void 0 ? void 0 : fetchRoomstayMember().then(() => {
                setIsLoading(false);
                onClose();
            });
        })
            .catch(() => {
            // This catch only fires if Promise.all itself rejects
            setIsLoading(false);
        });
    };
    const footers = (react_1.default.createElement("div", { className: "d-flex u-pad align-items-center justify-content-center" },
        react_1.default.createElement("div", { className: "u-marg-right" },
            react_1.default.createElement(BEButton_1.default, { isText: true, onClick: onClose }, t(Translation_1.Translation.Misc.Abort))),
        react_1.default.createElement(BEButton_1.default, { filled: true, primary: true, onClick: onCancelClick, isLoading: isLoading }, t(Translation_1.Translation.Misc.YesImSure))));
    return (react_1.default.createElement(SimpleModal_1.default, { title: t(Translation_1.Translation.Misc.CancellingReservation), open: visible, size: SimpleModal_1.SimpleModalSize.ExtraSmall, desktopFooter: footers, mobileFooter: footers, onClose: onClose },
        react_1.default.createElement("div", { className: "u-pad" },
            react_1.default.createElement(Text_1.default, null, t(Translation_1.Translation.Misc.ThisWillCancel)))));
};
const CodeNumberInformation = (props) => {
    const { itineraries, booking } = props;
    const { t } = (0, react_i18next_1.useTranslation)();
    const [cancelled, confirmed] = (0, react_1.useMemo)(() => {
        const cancelled = [];
        const confirmed = [];
        for (const item of itineraries) {
            if (item.status === core_1.EBookingStatus.Cancelled) {
                cancelled.push(item);
            }
            else {
                confirmed.push(item);
            }
        }
        return [cancelled, confirmed];
    }, itineraries);
    return (react_1.default.createElement(Card_1.Card, { className: "w-100", title: t(Translation_1.Translation.Reservation.CodeNumberInformation) },
        [
            { label: 'Cancelled', value: cancelled, type: Pill_1.PillType.Danger },
            { label: 'Confirmed', value: confirmed, type: Pill_1.PillType.Success },
        ].map((item, index) => {
            if (item.value.length > 0) {
                return (react_1.default.createElement(react_1.Fragment, { key: index },
                    react_1.default.createElement(Text_1.default, { className: "u-marg-right--light", inline: true, type: Text_1.TextType.Small }, item.label),
                    item.value.map((row, rowIndex) => {
                        return (react_1.default.createElement(react_1.Fragment, { key: rowIndex },
                            react_1.default.createElement(Text_1.default, { className: "u-marg-right", inline: true, type: Text_1.TextType.Small },
                                react_1.default.createElement(Pill_1.default, { type: item.type },
                                    "#",
                                    row.id))));
                    }),
                    react_1.default.createElement("br", null)));
            }
        }),
        react_1.default.createElement("div", { className: "u-marg-top" },
            react_1.default.createElement(Text_1.default, { className: "u-marg-right--light", inline: true, type: Text_1.TextType.Small }, t(Translation_1.Translation.UserPortal.ReservationSingleScreen.Itinerary)),
            react_1.default.createElement(Pill_1.default, { variant: Pill_1.PillVariant.Outlined, type: Pill_1.PillType.Grey },
                "#",
                booking.itineraryId))));
};
const IncludesTaxesMessage = ({ hotelId }) => {
    const { getPricesIncludeFeesMessage } = (0, react_1.useContext)(contexts_1.HotelOverridesContext);
    const { t } = (0, react_i18next_1.useTranslation)();
    const [message, setMessage] = (0, react_1.useState)(null);
    (0, react_1.useEffect)(() => {
        const init = () => __awaiter(void 0, void 0, void 0, function* () {
            const message = yield getPricesIncludeFeesMessage(hotelId);
            setMessage(message);
        });
        init();
    }, [hotelId, t, getPricesIncludeFeesMessage]);
    if (!message)
        return null;
    return (react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, color: Color_1.Color.DarkGrey },
        react_1.default.createElement("span", { dangerouslySetInnerHTML: { __html: message } })));
};
const AccountReservationSinglePage = () => {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const { t } = (0, react_i18next_1.useTranslation)();
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const beContext = (0, react_1.useContext)(contexts_1.BookingEngineContext);
    const { getHotel } = (0, react_1.useContext)(contexts_1.CompanyContext);
    const ccx = (0, react_1.useContext)(contexts_1.CompanyContext);
    const { getItinerary } = (0, LoggedInUserHook_1.useMember)();
    const [showingCancellationFor, setShowingCancellationFor] = (0, react_1.useState)(null);
    const [bookingHotel, setBookingHotel] = (0, react_1.useState)();
    const isMobile = beContext.screenSize <= ScreenSize_1.default.Medium;
    const params = (0, react_router_dom_1.useParams)();
    if (!params.navPath) {
        throw new Error('Missing reservation navPath parameter.');
    }
    const [booking, itineraries] = (0, react_1.useMemo)(() => {
        if (!params.resId) {
            throw new Error('Missing reservation ID parameter.');
        }
        const itineraries = [];
        const booking = getItinerary(params.resId);
        if (booking === null || booking === void 0 ? void 0 : booking.itinerary) {
            for (const itinerary of Object.values(booking.itinerary)) {
                itineraries.push(Object.assign(Object.assign({}, itinerary), { bookingId: booking.itineraryId, hotel: booking.hotel, hotelId: booking.hotelId }));
            }
        }
        return [booking, itineraries];
    }, [params, getItinerary]);
    (0, react_1.useEffect)(() => {
        if (booking === null || booking === void 0 ? void 0 : booking.hotelId) {
            getHotel(booking.hotelId).then((hotel) => {
                setBookingHotel(hotel);
            });
        }
    }, [booking === null || booking === void 0 ? void 0 : booking.hotelId, getHotel]);
    const allCancelled = (0, react_1.useMemo)(() => itineraries.every((row) => row.status === core_1.EBookingStatus.Cancelled), [itineraries]);
    const allCancellable = (0, react_1.useMemo)(() => itineraries.every((row) => row.isCancellable), [itineraries]);
    if (!booking) {
        return react_1.default.createElement(react_1.default.Fragment, null, t(Translation_1.Translation.Misc.Loading));
    }
    const { line1, line2, postalCode, country } = (_a = bookingHotel === null || bookingHotel === void 0 ? void 0 : bookingHotel.address) !== null && _a !== void 0 ? _a : {};
    const onActionClick = (action, item) => {
        switch (action) {
            case ReservationItem_1.ReservationAction.Cancel:
                setShowingCancellationFor([item]);
                break;
        }
    };
    const onCloseCancellationModal = () => {
        setShowingCancellationFor(null);
    };
    const onPrintClicked = () => {
        window.print();
    };
    const hotelImageElement = (hotel === null || hotel === void 0 ? void 0 : hotel.logo) && typeof hotel.logo !== 'string' ? hotel.logo : react_1.default.createElement("img", { src: typeof (hotel === null || hotel === void 0 ? void 0 : hotel.logo) === 'string' ? hotel.logo : ccx.logo, alt: "Hotel Logo", className: "u-block" });
    return (react_1.default.createElement("div", { id: `reservation-body-${booking.itineraryId}` },
        !!((_b = booking === null || booking === void 0 ? void 0 : booking.hotel) === null || _b === void 0 ? void 0 : _b.colors) && react_1.default.createElement("style", null, `#reservation-body-${booking.itineraryId} {${(0, Color_1.getAccentOverrideStyleContent)(booking.hotel.colors)}}`),
        react_1.default.createElement("div", { className: "u-marg-top--heavy@m u-marg-top@m- u-marg-bottom--light u-print-none" },
            react_1.default.createElement(react_router_dom_1.Link, { to: AccountRoutes_1.AccountRoutes.Reservations.path },
                react_1.default.createElement(BEButton_1.default, { isText: true, icon: Icon_1.IconType.ArrowLeft, size: "small" }, t(Translation_1.Translation.Reservation.BackToYourReservations)))),
        react_1.default.createElement("div", { className: "u-flex-align-stretch@m- u-flex u-flex-align-flex-end u-marg-bottom u-pad-top@m u-flex-direction-column@m- u-print-none" },
            react_1.default.createElement("div", null,
                react_1.default.createElement(Text_1.default, { className: "u-marg-bottom--light" }, StringHelper_1.default.pluralWithCount(itineraries.length, 'Room', t)),
                react_1.default.createElement(Headline_1.default, { size: "extra-large", className: "u-marg-bottom--light" }, getRoomNamesString(itineraries)),
                react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Body }, bookingHotel === null || bookingHotel === void 0 ? void 0 :
                    bookingHotel.name,
                    " \u2022 ",
                    [line1, line2, postalCode, country].filter((value) => !!value).join(' '))),
            react_1.default.createElement("div", { className: "u-flex u-flex-gap u-flex-direction-column@m- u-flex-gap--light@m- u-marg-top--heavy@m-" },
                react_1.default.createElement(BEButton_1.default, { wide: isMobile, rounded: isMobile, textColor: Color_1.Color.Navy, isText: !isMobile, icon: Icon_1.IconType.Share, iconPosition: "left" }, t(Translation_1.Translation.Reservation.Share)),
                react_1.default.createElement(BEButton_1.default, { wide: isMobile, mobileWidth: true, rounded: isMobile, textColor: Color_1.Color.Navy, className: "", isText: !isMobile, icon: Icon_1.IconType.Print, iconPosition: "left", onClick: onPrintClicked }, t(Translation_1.Translation.Reservation.Print)),
                !allCancelled && (react_1.default.createElement(react_1.default.Fragment, null,
                    ModifyBookingFeature_1.default.isActive() ? (react_1.default.createElement(BEButton_1.default, { wide: isMobile, mobileWidth: true, rounded: isMobile, textColor: Color_1.Color.Navy, isText: !isMobile, disabled: !allCancellable }, StringHelper_1.default.plural(itineraries.length, t(Translation_1.Translation.Reservation.ModifyReservation), t))) : null,
                    react_1.default.createElement(BEButton_1.default, { danger: true, wide: isMobile, mobileWidth: true, rounded: isMobile, textColor: Color_1.Color.Alert, isText: !isMobile, onClick: () => setShowingCancellationFor(itineraries), disabled: !allCancellable }, StringHelper_1.default.plural(itineraries.length, t(Translation_1.Translation.Reservation.CancelReservation), t)))))),
        react_1.default.createElement("span", { className: "u-print-none" },
            react_1.default.createElement(LineBreak_1.default, { smallMargins: true, fullBleed: true })),
        react_1.default.createElement(PrintOnly_1.default, null,
            react_1.default.createElement("div", { className: "c-header  d-inline-block" },
                react_1.default.createElement("div", { className: "c-header__logo u-flex u-flex-align-center" }, hotelImageElement))),
        react_1.default.createElement("div", { className: "u-marg-bottom--massive u-marg-bottom--none@m- u-print-marg-none u-marg-top--heavy" },
            react_1.default.createElement(ReservationList_1.default, { actions: [ReservationItem_1.ReservationAction.Cancel, ReservationItem_1.ReservationAction.Modify, ReservationItem_1.ReservationAction.BookAgain], reservationItems: itineraries, onActionClick: onActionClick, showCancelledNotifications: true, navPath: params.navPath })),
        react_1.default.createElement(LineBreak_1.default, { noMargins: isMobile }),
        react_1.default.createElement("div", { className: "u-flex u-marg-top--heavy@m-" },
            react_1.default.createElement(Headline_1.default, { size: "large", bold: true }, t(Translation_1.Translation.Reservation.Total)),
            react_1.default.createElement("div", { className: "u-flex align-items-end flex-column" },
                react_1.default.createElement(Headline_1.default, { lineThrough: true, size: "large", bold: true },
                    react_1.default.createElement(Currency_1.default, null, (0, core_1.calculateTotalForMemberBooking)(booking))),
                react_1.default.createElement(IncludesTaxesMessage, { hotelId: booking.hotelId }))),
        react_1.default.createElement("div", { className: "row u-marg-top--massive@m u-marg-top--heavy@m-" },
            react_1.default.createElement("div", { className: "col-md-4 u-flex u-print-col-md-4" },
                react_1.default.createElement(Card_1.Card, { className: "w-100", title: t(Translation_1.Translation.Navigation.Menu.PaymentInformation) },
                    react_1.default.createElement(IconText_1.default, { icon: Icon_1.IconType.Person }, ((_d = (_c = itineraries === null || itineraries === void 0 ? void 0 : itineraries[0]) === null || _c === void 0 ? void 0 : _c.profile) === null || _d === void 0 ? void 0 : _d.firstName) + ' ' + ((_f = (_e = itineraries === null || itineraries === void 0 ? void 0 : itineraries[0]) === null || _e === void 0 ? void 0 : _e.profile) === null || _f === void 0 ? void 0 : _f.lastName)),
                    react_1.default.createElement(IconText_1.default, { icon: Icon_1.IconType.Email }, (_h = (_g = itineraries === null || itineraries === void 0 ? void 0 : itineraries[0]) === null || _g === void 0 ? void 0 : _g.profile) === null || _h === void 0 ? void 0 : _h.email),
                    react_1.default.createElement(IconText_1.default, { icon: Icon_1.IconType.CreditCard, TextProps: { type: Text_1.TextType.Small } },
                        "\u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 \u2022\u2022\u2022\u2022 1111 ",
                        react_1.default.createElement("span", { style: { color: Color_1.Color.DarkGrey } }, "(Visa)")))),
            react_1.default.createElement("div", { className: "col-md-4 u-flex u-print-col-md-4" },
                react_1.default.createElement(Card_1.Card, { className: "w-100", title: t(Translation_1.Translation.Reservation.HotelInformation) },
                    react_1.default.createElement(IconText_1.default, { icon: Icon_1.IconType.Map },
                        line1,
                        react_1.default.createElement("br", null),
                        line2,
                        " ",
                        postalCode,
                        ", ",
                        country),
                    react_1.default.createElement(IconText_1.default, { icon: Icon_1.IconType.Phone }, bookingHotel === null || bookingHotel === void 0 ? void 0 : bookingHotel.phone))),
            react_1.default.createElement("div", { className: "col-md-4 u-flex u-print-col-md-4" },
                react_1.default.createElement(CodeNumberInformation, { itineraries: itineraries, booking: booking }))),
        react_1.default.createElement("div", { className: "u-marg-top--massive@m u-marg-top@m- u-background--snow u-w-fluid u-pad-top--massive@m u-pad-top--heavy@m- u-pad-bottom--heavy @m- u-pad-bottom--massive@m" },
            react_1.default.createElement("div", { className: "container" },
                react_1.default.createElement(Text_1.default, { bold: true },
                    " ",
                    t(Translation_1.Translation.Reservation.Policies)),
                react_1.default.createElement("div", { className: "u-marg-top--medium" },
                    react_1.default.createElement("div", { className: "u-w-100 row" },
                        react_1.default.createElement(GroupedCheckInOutTimes_1.GroupedCheckInOutTimes, { hotel: bookingHotel, wrapperClassName: "u-flex u-flex-direction-column@m- u-flex-gap--medium@m- col-6 col-md-3", colClassName: "", CheckInRender: () => (react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small },
                                react_1.default.createElement("strong", null, t(Translation_1.Translation.Misc.CheckIn)))), CheckOutRender: () => (react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small },
                                react_1.default.createElement("strong", null, t(Translation_1.Translation.Misc.CheckOut)))), LineRender: ({ line }) => react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small }, line) }))),
                react_1.default.createElement("div", { className: "u-marg-bottom" }, itineraries.map((itinerary, index) => (react_1.default.createElement("div", { key: index, className: "u-marg-top--heavy" },
                    react_1.default.createElement("div", { className: "u-marg-bottom" },
                        react_1.default.createElement(Text_1.default, { key: index, type: Text_1.TextType.Small },
                            react_1.default.createElement("strong", null,
                                t(Translation_1.Translation.Misc.Room),
                                " ",
                                index + 1),
                            "\u00A0",
                            itinerary.roomName,
                            " - ",
                            itinerary.rateName)),
                    react_1.default.createElement("div", { className: "u-marg-bottom" }, itinerary.guaranteePolicyLongDescription ? (react_1.default.createElement(react_1.default.Fragment, null,
                        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, bold: true, className: "u-marg-bottom--light" }, t(Translation_1.Translation.Misc.GuaranteePolicy)),
                        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small },
                            react_1.default.createElement("span", { dangerouslySetInnerHTML: { __html: itinerary.guaranteePolicyLongDescription || '' } })))) : null),
                    react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, bold: true, className: "u-marg-bottom--light" }, t(Translation_1.Translation.Misc.CancellationPolicy)),
                    react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small },
                        react_1.default.createElement("span", { dangerouslySetInnerHTML: { __html: itinerary.cancellationPolicyLongDescription || '' } })))))))),
        react_1.default.createElement(CancelReservationModal, { onClose: onCloseCancellationModal, items: showingCancellationFor, booking: booking, visible: !!showingCancellationFor })));
};
exports.AccountReservationSinglePage = AccountReservationSinglePage;
//# sourceMappingURL=AccountReservationSinglePage.js.map