"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.ForgotPasswordForm = 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 BEButton_1 = __importDefault(require("../../generic/BEButton"));
const Headline_1 = __importDefault(require("../../generic/Headline"));
const Text_1 = __importStar(require("../../generic/Text"));
const TextBox_1 = __importDefault(require("../../generic/TextBox"));
const Color_1 = require("../../../util/Color");
const Validation_1 = require("../../../util/Validation");
const PasswordBox_1 = require("../../generic/PasswordBox/PasswordBox");
const LabelAndInputGroup = (props) => {
    const { label, component, error } = props;
    return (react_1.default.createElement("div", { className: "u-marg-bottom--light" },
        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 }, label)),
        component,
        !!error && (react_1.default.createElement("p", { className: "text-small", style: { color: '#ED4362' } }, error.message))));
};
const ForgotPasswordForm = (props) => {
    const { t } = (0, react_i18next_1.useTranslation)();
    const { cognitoLoginState, loading: cognitoLoading, forgotPassword, resetPassword, reset, setPendingCredentials } = (0, react_1.useContext)(contexts_1.AuthenticationContext);
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const { register, trigger, formState, handleSubmit, watch, setError } = (0, react_hook_form_1.useForm)({
        mode: 'onSubmit',
    });
    const passwordWatch = watch('password');
    (0, react_1.useEffect)(() => {
        trigger('confirmPassword');
    }, [passwordWatch, trigger]);
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const getValidationClass = (name) => {
        if (formState.errors) {
            if (formState.errors[name]) {
                return 'error';
            }
            else {
                return 'success';
            }
        }
    };
    const forgotPasswordStates = [contexts_1.CognitoLoginState.ForgotPassword, contexts_1.CognitoLoginState.CodeMismatch];
    const areResettingPassword = forgotPasswordStates.includes(cognitoLoginState);
    const onSubmit = (values) => __awaiter(void 0, void 0, void 0, function* () {
        var _a, _b, _c, _d;
        setIsLoading(true);
        try {
            if (areResettingPassword) {
                const state = yield resetPassword(values.email, values.code, values.password, { hotel });
                if (state === contexts_1.CognitoLoginState.CodeMismatch) {
                    setError('code', {
                        message: t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.Code.Validation.InvalidCode),
                    });
                }
                else if (state === contexts_1.CognitoLoginState.Success) {
                    (_a = props.onPasswordReset) === null || _a === void 0 ? void 0 : _a.call(props);
                    (_b = props.onDone) === null || _b === void 0 ? void 0 : _b.call(props);
                }
                else {
                    (_c = props.onDone) === null || _c === void 0 ? void 0 : _c.call(props);
                }
            }
            else {
                const state = yield forgotPassword(values.email, { hotel });
                if (state === contexts_1.CognitoLoginState.UserNotFound) {
                    setError('email', {
                        message: t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.Email.Validation.UserNotFound),
                    });
                }
                else if (state === contexts_1.CognitoLoginState.RequiresConfirmation) {
                    setPendingCredentials({ email: values.email });
                    (_d = props.onNotVerified) === null || _d === void 0 ? void 0 : _d.call(props);
                }
            }
        }
        catch (ex) {
            console.error(ex);
        }
        finally {
            setIsLoading(false);
        }
    });
    const onCancelPressed = () => {
        var _a;
        reset();
        (_a = props.onCancelled) === null || _a === void 0 ? void 0 : _a.call(props);
    };
    return (react_1.default.createElement("div", null,
        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.ForgotPassword.Title)),
            areResettingPassword && (react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, color: Color_1.Color.Success }, t(Translation_1.Translation.Navigation.ForgotPassword.CodeSent)))),
        react_1.default.createElement("form", { onSubmit: handleSubmit(onSubmit) },
            react_1.default.createElement(LabelAndInputGroup, { label: t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.Email.Label), error: formState.errors.email, component: react_1.default.createElement(TextBox_1.default, Object.assign({ placeholder: t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.Email.Placeholder), required: true, validationStatus: getValidationClass('email'), inputProps: { disabled: areResettingPassword || isLoading || cognitoLoading } }, register('email', {
                    required: true,
                    pattern: (0, Validation_1.makeEmailPatternRule)(t),
                }))) }),
            react_1.default.createElement(AutoAutoHeight_1.default, { open: areResettingPassword },
                react_1.default.createElement(LabelAndInputGroup, { label: t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.Code.Label), error: formState.errors.code, component: react_1.default.createElement(TextBox_1.default, Object.assign({ placeholder: t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.Code.Placeholder), validationStatus: getValidationClass('code'), inputProps: { disabled: isLoading || cognitoLoading } }, register('code', {
                        required: (0, Validation_1.makeRequiredRule)(t)(areResettingPassword, t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.Code.Label)),
                    }))) }),
                react_1.default.createElement(LabelAndInputGroup, { label: t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.Password.Label), error: formState.errors.password, component: react_1.default.createElement(PasswordBox_1.PasswordBox, Object.assign({ placeholder: t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.Password.Placeholder), validationStatus: getValidationClass('password'), inputProps: { disabled: isLoading || cognitoLoading } }, register('password', {
                        required: (0, Validation_1.makeRequiredRule)(t)(areResettingPassword, t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.Password.Label)),
                        pattern: (0, Validation_1.makePasswordPatternRule)(t),
                    }))) }),
                react_1.default.createElement(LabelAndInputGroup, { label: t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.RepeatPassword.Label), error: formState.errors.confirmPassword, component: react_1.default.createElement(PasswordBox_1.PasswordBox, Object.assign({ placeholder: t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.RepeatPassword.Placeholder), validationStatus: getValidationClass('confirmPassword'), inputProps: { disabled: isLoading || cognitoLoading } }, register('confirmPassword', {
                        required: (0, Validation_1.makeRequiredRule)(t)(areResettingPassword, t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.RepeatPassword.Label)),
                        validate: {
                            isSame: (0, Validation_1.isPasswordMatch)(t)(passwordWatch),
                        },
                    }))) })),
            react_1.default.createElement("div", { className: "u-marg-top" },
                react_1.default.createElement(BEButton_1.default, { primary: true, filled: true, wide: true, htmlType: "submit", isLoading: cognitoLoading || isLoading }, t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.SubmitButton.Label))),
            react_1.default.createElement("div", { className: "u-marg-top u-align-center" },
                react_1.default.createElement(BEButton_1.default, { isText: true, onClick: onCancelPressed, size: "small" }, t(Translation_1.Translation.Navigation.ForgotPassword.Inputs.CancelButton.Label))))));
};
exports.ForgotPasswordForm = ForgotPasswordForm;
//# sourceMappingURL=ForgotPasswordForm.js.map