"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.SignUpForm = void 0;
const contexts_1 = require("../../../contexts/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 Translation_1 = require("translations/Translation");
const AutoAutoHeight_1 = __importDefault(require("../../../animations/AutoAutoHeight"));
const Alert_1 = __importStar(require("../../generic/Alert"));
const BEButton_1 = __importDefault(require("../../generic/BEButton"));
const Checkbox_1 = __importDefault(require("../../generic/Checkbox/Checkbox"));
const Headline_1 = __importDefault(require("../../generic/Headline"));
const Icon_1 = require("../../generic/Icon/Icon");
const InputGroup_1 = __importDefault(require("../../generic/InputGroup/InputGroup"));
const Text_1 = __importStar(require("../../generic/Text"));
const TextBox_1 = __importDefault(require("../../generic/TextBox"));
const VerifyEmailForm_1 = require("./VerifyEmailForm");
const Color_1 = require("../../../util/Color");
const Validation_1 = require("../../../util/Validation");
const PasswordBox_1 = require("../../generic/PasswordBox/PasswordBox");
const SignUpForm_module_scss_1 = __importDefault(require("./SignUpForm.module.scss"));
const SignUpForm = (props) => {
    var _a, _b, _c;
    const { t } = (0, react_i18next_1.useTranslation)();
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const ccx = (0, react_1.useContext)(contexts_1.CompanyContext);
    const { loading, error, cognitoLoginState, register: cognitoRegister, reset: cognitoReset, setPendingCredentials } = (0, react_1.useContext)(contexts_1.AuthenticationContext);
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const [, setApiErrorMessages] = (0, react_1.useState)('');
    const [isVerifyingEmail, setIsVerifyingEmail] = (0, react_1.useState)(cognitoLoginState === contexts_1.CognitoLoginState.RequiresConfirmation);
    const { register, formState, handleSubmit } = (0, react_hook_form_1.useForm)({
        mode: 'onSubmit',
        defaultValues: {
            email: ((_a = props.defaultValues) === null || _a === void 0 ? void 0 : _a.email) || '',
            forename: ((_b = props.defaultValues) === null || _b === void 0 ? void 0 : _b.firstName) || '',
            surname: ((_c = props.defaultValues) === null || _c === void 0 ? void 0 : _c.lastName) || '',
            password: '',
            termsAndConditions: false,
        },
    });
    const signUpStates = [contexts_1.CognitoLoginState.UsernameExists];
    const errors = formState.errors;
    const accountExists = signUpStates.includes(cognitoLoginState);
    const getValidationClass = (name) => {
        if (errors && formState.touchedFields[name]) {
            if (errors[name]) {
                return 'error';
            }
            else {
                return 'success';
            }
        }
    };
    const onSubmit = (values) => __awaiter(void 0, void 0, void 0, function* () {
        setIsLoading(true);
        setApiErrorMessages('');
        try {
            const state = yield cognitoRegister(values.email, values.password, {
                ['custom:forename']: values.forename,
                ['custom:surname']: values.surname,
            }, { hotel });
            if (state === contexts_1.CognitoLoginState.RequiresConfirmation) {
                setPendingCredentials({ email: values.email, password: values.password });
                setIsVerifyingEmail(true);
            }
        }
        finally {
            setIsLoading(false);
        }
    });
    const onSignInClicked = () => {
        var _a;
        cognitoReset();
        (_a = props.onSignIn) === null || _a === void 0 ? void 0 : _a.call(props);
    };
    const onErrorContent = () => {
        switch (cognitoLoginState) {
            case contexts_1.CognitoLoginState.UsernameExists: {
                return (react_1.default.createElement(react_1.default.Fragment, null,
                    react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small },
                        react_1.default.createElement(react_i18next_1.Trans, { i18nKey: Translation_1.Translation.Navigation.SignUp.EmailIsInUse, components: [react_1.default.createElement(BEButton_1.default, { key: 0, isText: true, size: "small", primary: true, onClick: onSignInClicked })] }))));
            }
        }
    };
    return (react_1.default.createElement("div", { className: `${props.reduceMargins ? SignUpForm_module_scss_1.default['signup-form--reduced-margins'] : ''}` },
        !props.hideTitle && (react_1.default.createElement("div", { className: "u-marg-bottom--heavy" },
            react_1.default.createElement(Headline_1.default, { color: Color_1.Color.Navy, bold: true, className: "u-marg-bottom--light" }, t(Translation_1.Translation.Navigation.SignUp.Title)))),
        react_1.default.createElement(AutoAutoHeight_1.default, { open: !!accountExists },
            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 }, onErrorContent()))),
        react_1.default.createElement(AutoAutoHeight_1.default, { open: !!error },
            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 }, error === null || error === void 0 ? void 0 : error.message)))),
        react_1.default.createElement(AutoAutoHeight_1.default, { open: !!formState.errors },
            react_1.default.createElement("div", { className: "u-flex flex-column" }, Object.keys(formState.errors).map((errorName, index) => {
                var _a;
                return (react_1.default.createElement(Alert_1.default, { type: Alert_1.AlertType.Danger, icon: Icon_1.IconType.Error, key: index },
                    react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small }, (_a = formState.errors[errorName]) === null || _a === void 0 ? void 0 : _a.message)));
            }))),
        react_1.default.createElement(AutoAutoHeight_1.default, { open: !isVerifyingEmail, startOpen: true },
            react_1.default.createElement("form", { onSubmit: handleSubmit(onSubmit), className: "u-marg-bottom" },
                react_1.default.createElement("div", { className: "u-marg-bottom" },
                    react_1.default.createElement(InputGroup_1.default, { dimensions: "2/2", noMargin: props.reduceMargins },
                        react_1.default.createElement(react_1.default.Fragment, null,
                            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, bold: true }, t(Translation_1.Translation.Navigation.SignUp.Inputs.FirstName))),
                            react_1.default.createElement(TextBox_1.default, Object.assign({ inputProps: { disabled: loading || isLoading }, placeholder: "Sam", validationStatus: getValidationClass('forename') }, register('forename', {
                                required: (0, Validation_1.makeRequiredRule)(t)(true, t(Translation_1.Translation.Navigation.SignUp.Inputs.FirstName)),
                            })))),
                        react_1.default.createElement(react_1.default.Fragment, null,
                            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, bold: true }, t(Translation_1.Translation.Navigation.SignUp.Inputs.LastName))),
                            react_1.default.createElement(TextBox_1.default, Object.assign({ inputProps: { disabled: loading || isLoading }, placeholder: "Smith", validationStatus: getValidationClass('surname') }, register('surname', {
                                required: (0, Validation_1.makeRequiredRule)(t)(true, t(Translation_1.Translation.Navigation.SignUp.Inputs.LastName)),
                            })))))),
                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, bold: true }, t(Translation_1.Translation.Navigation.SignIn.EmailAddress))),
                    react_1.default.createElement(TextBox_1.default, Object.assign({ inputProps: { disabled: loading || isLoading }, placeholder: "example@mail.com", validationStatus: getValidationClass('email') }, register('email', {
                        required: (0, Validation_1.makeRequiredRule)(t)(true, t(Translation_1.Translation.Navigation.SignIn.EmailAddress)),
                        pattern: {
                            value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
                            message: t(Translation_1.Translation.FindReservation.InvalidEmailAddress),
                        },
                    })))),
                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, bold: true }, t(Translation_1.Translation.Navigation.SignUp.Inputs.Password.Label))),
                    react_1.default.createElement("div", { className: "u-marg-bottom--light" },
                        react_1.default.createElement(PasswordBox_1.PasswordBox, Object.assign({ inputProps: { disabled: loading || isLoading }, placeholder: t(Translation_1.Translation.Navigation.SignUp.Inputs.Password.Label), validationStatus: getValidationClass('password') }, register('password', {
                            required: (0, Validation_1.makeRequiredRule)(t)(true, t(Translation_1.Translation.Navigation.SignUp.Inputs.Password.Label)),
                            pattern: (0, Validation_1.makePasswordPatternRule)(t),
                        })))),
                    react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label, color: Color_1.Color.Navy, className: "u-marg-bottom password-hint" }, t(Translation_1.Translation.Navigation.SignUp.Inputs.Password.Hint)),
                    react_1.default.createElement(Checkbox_1.default, Object.assign({ label: react_1.default.createElement("div", null,
                            t(Translation_1.Translation.Navigation.SignUp.Inputs.Terms.BaseText),
                            ' ',
                            react_1.default.createElement("a", { href: (hotel === null || hotel === void 0 ? void 0 : hotel.privacyPolicyUrl) || (ccx === null || ccx === void 0 ? void 0 : ccx.privacyPolicyUrl), target: "_blank", style: { color: Color_1.Color.Accent }, rel: "noreferrer" }, t(Translation_1.Translation.Navigation.SignUp.Inputs.Terms.LinkText))) }, register('termsAndConditions', {
                        required: {
                            value: true,
                            message: t(Translation_1.Translation.Navigation.SignUp.Inputs.Terms.Error),
                        },
                    })))),
                react_1.default.createElement(BEButton_1.default, { wide: true, icon: Icon_1.IconType.ArrowRight, iconPosition: "right", filled: true, primary: true, name: "SignUpButton", htmlType: "submit", isLoading: loading || isLoading, disabled: isLoading || loading }, t(Translation_1.Translation.Navigation.SignUp.Inputs.SignUpButton)))),
        react_1.default.createElement(AutoAutoHeight_1.default, { open: isVerifyingEmail },
            react_1.default.createElement(VerifyEmailForm_1.VerifyEmailForm, { onDone: props.onDone, onSignIn: props.onSignIn })),
        react_1.default.createElement("div", { className: "u-marg-top--light" },
            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label, color: Color_1.Color.DarkGrey },
                react_1.default.createElement("span", { dangerouslySetInnerHTML: { __html: t(Translation_1.Translation.MemberOnlyPopup.AgreeToReceiveDeals, { companyShort: ccx === null || ccx === void 0 ? void 0 : ccx.companyShort }) } })),
            ' ',
            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Label, color: Color_1.Color.DarkGrey },
                react_1.default.createElement("span", { dangerouslySetInnerHTML: { __html: t(Translation_1.Translation.MemberOnlyPopup.UnsubscribeAnytime) } })))));
};
exports.SignUpForm = SignUpForm;
//# sourceMappingURL=SignUpForm.js.map