"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.EFindReservationPath = void 0;
exports.default = FindReservation;
const events_1 = require("../../events/index.js");
const hooks_1 = require("../../hooks/index.js");
const react_1 = __importStar(require("react"));
const react_hook_form_1 = require("react-hook-form");
const react_i18next_1 = require("react-i18next");
const react_router_dom_1 = require("react-router-dom");
const Translation_1 = require("translations/Translation");
const AutoAutoHeight_1 = __importDefault(require("../../animations/AutoAutoHeight"));
const Fade_1 = __importDefault(require("../../animations/Fade"));
const BookingAPI_1 = __importDefault(require("../../api/BookingAPI"));
const Alert_1 = __importStar(require("../../components/generic/Alert"));
const BEButton_1 = __importDefault(require("../../components/generic/BEButton"));
const Headline_1 = __importDefault(require("../../components/generic/Headline"));
const Icon_1 = require("../../components/generic/Icon/Icon");
const LineBreak_1 = __importDefault(require("../../components/generic/LineBreak"));
const SmallSpinner_1 = __importDefault(require("../../components/generic/loader/SmallSpinner"));
const UnauthenticatedUserModal_1 = require("../../components/generic/modal/SigninModal/UnauthenticatedUserModal");
const PageTitle_1 = require("../../components/generic/PageTitle");
const Text_1 = __importStar(require("../../components/generic/Text"));
const TextBox_1 = __importDefault(require("../../components/generic/TextBox"));
const contexts_1 = require("../../contexts");
const MemberPortalFeature_1 = __importDefault(require("../../providers/feature/MemberPortalFeature"));
const ImageProvider_1 = __importStar(require("../../providers/ImageProvider"));
const RoomstayThemeEngine_1 = __importDefault(require("../../providers/RoomstayThemeEngine"));
const Color_1 = require("../../util/Color");
const StepManager_1 = __importDefault(require("../../util/StepManager"));
const Validation_1 = require("../../util/Validation");
const SignInForm = react_1.default.lazy(() => Promise.resolve().then(() => __importStar(require('../../components/User/Forms/SignInForm'))).then(({ SignInForm }) => ({
    default: SignInForm,
})));
const SignUpForm = react_1.default.lazy(() => Promise.resolve().then(() => __importStar(require('../../components/User/Forms/SignUpForm'))).then(({ SignUpForm }) => ({
    default: SignUpForm,
})));
const ForgotPasswordForm = react_1.default.lazy(() => Promise.resolve().then(() => __importStar(require('../../components/User/Forms/ForgotPasswordForm'))).then(({ ForgotPasswordForm }) => ({
    default: ForgotPasswordForm,
})));
var EFindReservationPath;
(function (EFindReservationPath) {
    EFindReservationPath["FindReservation"] = "find-reservation";
    EFindReservationPath["Login"] = "login";
    EFindReservationPath["Register"] = "register";
    EFindReservationPath["Forgot"] = "forgot";
})(EFindReservationPath || (exports.EFindReservationPath = EFindReservationPath = {}));
const pathToScreenMapping = {
    [EFindReservationPath.FindReservation]: UnauthenticatedUserModal_1.EViewingScreen.Default,
    [EFindReservationPath.Login]: UnauthenticatedUserModal_1.EViewingScreen.SignIn,
    [EFindReservationPath.Register]: UnauthenticatedUserModal_1.EViewingScreen.SignUp,
    [EFindReservationPath.Forgot]: UnauthenticatedUserModal_1.EViewingScreen.ForgotPassword,
};
function FindReservation() {
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const { t } = (0, react_i18next_1.useTranslation)();
    const { cognitoLoginState } = (0, contexts_1.useAuthentication)();
    const { register, formState, handleSubmit, getValues } = (0, react_hook_form_1.useForm)({
        mode: 'onChange',
    });
    const errors = formState.errors;
    const getValidationClass = (name) => {
        if (errors && formState.touchedFields[name]) {
            if (errors[name]) {
                return 'error';
            }
            else {
                return 'success';
            }
        }
    };
    const firstTime = (0, react_1.useRef)(true);
    const nextViewingScreen = (0, react_1.useRef)(null);
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const [apiErrorMessages, setApiErrorMessages] = (0, react_1.useState)('');
    const navigate = (0, react_router_dom_1.useNavigate)();
    const location = (0, react_router_dom_1.useLocation)();
    const path = location.pathname.replace('/', '');
    const [viewingScreen, setViewingScreen] = (0, react_1.useState)(pathToScreenMapping[path]);
    (0, react_1.useEffect)(() => {
        if (cognitoLoginState === contexts_1.CognitoLoginState.Success) {
            navigate(`/${EFindReservationPath.FindReservation}`);
            firstTime.current = false;
            setViewingScreen(UnauthenticatedUserModal_1.EViewingScreen.Default);
            nextViewingScreen.current = UnauthenticatedUserModal_1.EViewingScreen.Default;
        }
        else {
            if (firstTime.current) {
                firstTime.current = false;
                setViewingScreen(pathToScreenMapping[path]);
            }
            else {
                if (cognitoLoginState !== contexts_1.CognitoLoginState.ForgotPassword)
                    setViewingScreen(null);
                nextViewingScreen.current = pathToScreenMapping[path];
            }
        }
    }, [path, cognitoLoginState]);
    const onSubmit = () => {
        setIsLoading(true);
        setApiErrorMessages('');
        BookingAPI_1.default.Reservation.findReservation(getValues('Ref'), getValues('Email'), hotel === null || hotel === void 0 ? void 0 : hotel.hotelID)
            .then((data) => {
            navigate(`/find-reservation/${getValues('Ref')}/${getValues('Email')}`);
        })
            .catch(({ Message }) => {
            console.log(Message);
            setApiErrorMessages(Message);
            setIsLoading(false);
        });
    };
    const { raise } = (0, hooks_1.useEvent)();
    (0, react_1.useEffect)(() => {
        if (!(hotel === null || hotel === void 0 ? void 0 : hotel.hotelID) || !(hotel === null || hotel === void 0 ? void 0 : hotel.heroImage) || !(RoomstayThemeEngine_1.default === null || RoomstayThemeEngine_1.default === void 0 ? void 0 : RoomstayThemeEngine_1.default.EngineContainer))
            return;
        const backgroundId = 'rs-background-find-reservation';
        const existingBg = document.getElementById(backgroundId);
        if (existingBg) {
            RoomstayThemeEngine_1.default.EngineContainer.removeChild(existingBg);
        }
        const background = document.createElement('div');
        background.id = backgroundId;
        background.classList.add('dbe-background', 'rs-background-find-reservation', `rs-background-${hotel === null || hotel === void 0 ? void 0 : hotel.hotelID}`);
        background.style.backgroundImage = `url('${(hotel === null || hotel === void 0 ? void 0 : hotel.heroImage) && ImageProvider_1.default.resizeImage(hotel === null || hotel === void 0 ? void 0 : hotel.heroImage, ImageProvider_1.ImageSize.Original)}')`;
        RoomstayThemeEngine_1.default.EngineContainer.classList.add('--transparent-bg');
        RoomstayThemeEngine_1.default.EngineContainer.appendChild(background);
        const event = new events_1.FindReservationViewEvent();
        raise(event);
        return () => {
            try {
                const bg = document.getElementById(backgroundId);
                if (bg) {
                    RoomstayThemeEngine_1.default.EngineContainer.removeChild(bg);
                }
                RoomstayThemeEngine_1.default.EngineContainer.classList.remove('--transparent-bg');
            }
            catch (ex) {
                console.log('Unable to remove bg');
            }
        };
    }, [hotel === null || hotel === void 0 ? void 0 : hotel.hotelID, hotel === null || hotel === void 0 ? void 0 : hotel.heroImage]);
    (0, react_1.useEffect)(() => {
        if (hotel === null || hotel === void 0 ? void 0 : hotel.forwardFindReservationToSynxis) {
            window.open(`https://be.synxis.com/signin?hotel=` + hotel.hotelID);
        }
    }, [hotel === null || hotel === void 0 ? void 0 : hotel.hotelID, hotel === null || hotel === void 0 ? void 0 : hotel.forwardFindReservationToSynxis]);
    const onBack = () => __awaiter(this, void 0, void 0, function* () {
        navigate(StepManager_1.default.getFirstStep().getStepUrl());
    });
    const handleSubmitOnClick = () => {
        handleSubmit(onSubmit)();
    };
    const onSignInClicked = () => {
        navigate(`/${EFindReservationPath.Login}`);
    };
    const onBackToItineraryClicked = () => {
        navigate(`/${EFindReservationPath.FindReservation}`);
    };
    const onSignUpClicked = () => {
        navigate(`/${EFindReservationPath.Register}`);
    };
    const onForgotPasswordClicked = () => {
        navigate(`/${EFindReservationPath.Forgot}`);
    };
    const onExit = () => {
        setViewingScreen(nextViewingScreen.current);
    };
    const gotoReservationPage = () => {
        navigate(`/account/reservations`);
    };
    const defaultContents = (react_1.default.createElement("form", { onSubmit: handleSubmit(onSubmit) },
        react_1.default.createElement("div", { className: "u-marg-bottom--heavy" },
            react_1.default.createElement(Headline_1.default, { size: "extra-large" }, t(Translation_1.Translation.FindReservation.FindYourReservation))),
        react_1.default.createElement(AutoAutoHeight_1.default, { open: !!apiErrorMessages },
            react_1.default.createElement("div", { className: "u-flex" },
                react_1.default.createElement(Alert_1.default, { type: Alert_1.AlertType.Danger, icon: Icon_1.IconType.Error },
                    react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small }, apiErrorMessages)))),
        react_1.default.createElement("div", { className: "u-marg-bottom" },
            react_1.default.createElement("div", { className: "u-marg-bottom--light" },
                react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label, color: Color_1.Color.Navy },
                    react_1.default.createElement("strong", null, t(Translation_1.Translation.FindReservation.Confirmation)))),
            react_1.default.createElement(TextBox_1.default, Object.assign({ placeholder: "51244AB23101", required: true, validationStatus: getValidationClass('Ref') }, register('Ref', {
                required: true,
            })))),
        react_1.default.createElement("div", { className: "u-marg-bottom" },
            react_1.default.createElement("div", { className: "u-marg-bottom--light" },
                react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label, color: Color_1.Color.Navy },
                    react_1.default.createElement("strong", null, t(Translation_1.Translation.FindReservation.EmailAddress)))),
            react_1.default.createElement(TextBox_1.default, Object.assign({ placeholder: "example@mail.com", required: true, validationStatus: getValidationClass('Email') }, register('Email', {
                required: true,
                pattern: {
                    value: Validation_1.EMAIL_REGEX,
                    message: t(Translation_1.Translation.FindReservation.InvalidEmailAddress),
                },
            })))),
        react_1.default.createElement("div", { className: "u-flex justify-content-end w-100" },
            react_1.default.createElement(BEButton_1.default, { primary: true, filled: true, mobileWidth: true, isLoading: isLoading, icon: Icon_1.IconType.ArrowRight, iconPosition: "right", onClick: handleSubmitOnClick }, t(Translation_1.Translation.FindReservation.FindReservation)),
            react_1.default.createElement("button", { type: "submit", className: "u-none" }, t(Translation_1.Translation.Misc.Submit))),
        MemberPortalFeature_1.default.isActive() && cognitoLoginState === contexts_1.CognitoLoginState.Success && (react_1.default.createElement("div", { className: "u-align-right u-flex u-flex-flex-end u-flex-gap--light u-marg-top--light" },
            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small }, t(Translation_1.Translation.Navigation.SignIn.Or)),
            react_1.default.createElement(BEButton_1.default, { isText: true, primary: true, size: "small", onClick: gotoReservationPage, icon: Icon_1.IconType.ArrowRight, iconPosition: "right" }, t(Translation_1.Translation.FindReservation.GoToYourReservations)))),
        react_1.default.createElement(LineBreak_1.default, null),
        MemberPortalFeature_1.default.isActive() && cognitoLoginState !== contexts_1.CognitoLoginState.Success && (react_1.default.createElement("div", { className: "u-marg-bottom--heavy" },
            react_1.default.createElement(BEButton_1.default, { isText: true, primary: true, size: "small", onClick: onSignInClicked }, "Or sign in for more"))),
        react_1.default.createElement("div", { className: "u-marg-bottom--light" },
            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small },
                react_1.default.createElement("strong", null, t(Translation_1.Translation.FindReservation.Question)))),
        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small }, t(Translation_1.Translation.FindReservation.Answer1)),
        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small }, t(Translation_1.Translation.FindReservation.Answer2)),
        react_1.default.createElement(LineBreak_1.default, null),
        react_1.default.createElement(BEButton_1.default, { textColor: Color_1.Color.Accent, primary: false, filled: false, mobileWidth: true, size: "small", icon: Icon_1.IconType.ArrowLeft2, iconPosition: "left", onClick: onBack, isText: true }, t(Translation_1.Translation.FindReservation.Back))));
    const signInForm = (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(SignInForm, { onForgotPassword: onForgotPasswordClicked, onDone: () => {
                gotoReservationPage();
            } }),
        react_1.default.createElement(LineBreak_1.default, null),
        react_1.default.createElement("div", { className: "u-marg-bottom--heavy" },
            react_1.default.createElement(BEButton_1.default, { isText: true, primary: true, size: "small", onClick: onBackToItineraryClicked }, t(Translation_1.Translation.FindReservation.OrUseConfirmationItineraryNumber))),
        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, bold: true, className: "u-marg-bottom--light" }, t(Translation_1.Translation.FindReservation.NoOnlineAccount)),
        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small },
            react_1.default.createElement(react_i18next_1.Trans, { i18nKey: Translation_1.Translation.FindReservation.SignUpToSaveTime, components: [react_1.default.createElement(BEButton_1.default, { key: 0, isText: true, size: "small", primary: true, onClick: onSignUpClicked })] }))));
    const signUpForm = (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(SignUpForm, { onDone: () => {
                gotoReservationPage();
            } }),
        react_1.default.createElement(LineBreak_1.default, null),
        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, bold: true, className: "u-marg-bottom--light" }, t(Translation_1.Translation.Step.Confirmation.AlreadyHaveAccount)),
        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small },
            react_1.default.createElement(react_i18next_1.Trans, { i18nKey: Translation_1.Translation.FindReservation.SignInToLogin, components: [react_1.default.createElement(BEButton_1.default, { key: 0, isText: true, size: "small", primary: true, onClick: onSignInClicked })] }))));
    const forgotPasswordForm = (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(ForgotPasswordForm, { onCancelled: onSignInClicked, onDone: () => {
                gotoReservationPage();
            } }),
        react_1.default.createElement(LineBreak_1.default, null),
        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, bold: true, className: "u-marg-bottom--light" }, t(Translation_1.Translation.FindReservation.NoOnlineAccount)),
        react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small },
            react_1.default.createElement(react_i18next_1.Trans, { i18nKey: Translation_1.Translation.FindReservation.SignUpToSaveTime, components: [react_1.default.createElement(BEButton_1.default, { key: 0, isText: true, size: "small", primary: true, onClick: onSignUpClicked })] }))));
    return (react_1.default.createElement("div", { className: "u-pad-left u-pad-right" },
        react_1.default.createElement(PageTitle_1.PageTitle, { step: "FindReservation" }),
        react_1.default.createElement("div", { className: "container u-marg-top--heavy u-pad-bottom--massive" },
            react_1.default.createElement("div", { className: "row u-pad-bottom--massive" },
                react_1.default.createElement("div", { className: "col-md-6 col-xl-4 u-fill-white u-pad--heavy u-shadow-accent-large u-border-rounded" },
                    react_1.default.createElement(AutoAutoHeight_1.default, { open: true, startOpen: true },
                        react_1.default.createElement(Fade_1.default, { open: viewingScreen === 'Default', onExitCompletely: onExit }, defaultContents),
                        react_1.default.createElement(react_1.Suspense, { fallback: SmallSpinner_1.default },
                            react_1.default.createElement(Fade_1.default, { open: viewingScreen === 'SignIn', onExitCompletely: onExit }, signInForm),
                            react_1.default.createElement(Fade_1.default, { open: viewingScreen === 'SignUp', onExitCompletely: onExit }, signUpForm),
                            react_1.default.createElement(Fade_1.default, { open: viewingScreen === 'ForgotPassword', onExitCompletely: onExit }, forgotPasswordForm))))))));
}
//# sourceMappingURL=FindReservation.js.map