"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 });
const core_1 = require("@roomstay/core");
const classnames_1 = __importDefault(require("classnames"));
const react_1 = __importStar(require("react"));
const react_hook_form_1 = require("react-hook-form");
const react_i18next_1 = require("react-i18next");
const BookingAPI_1 = __importDefault(require("../../../api/BookingAPI"));
const BEButton_1 = __importDefault(require("../../generic/BEButton"));
const Headline_1 = __importDefault(require("../../generic/Headline"));
const Icon_1 = require("../../generic/Icon/Icon");
const InputGroup_1 = __importDefault(require("../../generic/InputGroup/InputGroup"));
const SimpleModal_1 = __importStar(require("../../generic/modal/SimpleModal"));
const PasswordBox_1 = require("../../generic/PasswordBox/PasswordBox");
const Text_1 = __importStar(require("../../generic/Text"));
const TextBox_1 = __importDefault(require("../../generic/TextBox"));
const contexts_1 = require("../../../contexts");
const hooks_1 = require("../../../hooks");
const ImageProvider_1 = __importStar(require("../../../providers/ImageProvider"));
const Translation_1 = require("../../../translations/Translation");
const Color_1 = require("../../../util/Color");
const ExternalMemberModal_module_scss_1 = __importDefault(require("./ExternalMemberModal.module.scss"));
const ExternalMemberModal = (props) => {
    var _a;
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const basketContext = (0, react_1.useContext)(contexts_1.BasketContext);
    const { signUserIn, closeMemberSignupModal } = (0, react_1.useContext)(contexts_1.CompanyContext);
    const { t } = (0, react_i18next_1.useTranslation)();
    const [isLoading, setIsLoading] = (0, react_1.useState)(false);
    const [errorMessage, setErrorMessage] = (0, react_1.useState)('');
    const formMethods = (0, react_hook_form_1.useForm)();
    const modalPrimaryColor = (hotel === null || hotel === void 0 ? void 0 : hotel.memberOnlyModalUsePrimaryColor) ? Color_1.Color.Accent : Color_1.Color.Success;
    const memberOnlySignupLink = (_a = hotel === null || hotel === void 0 ? void 0 : hotel.memberOnlySignupLinks) === null || _a === void 0 ? void 0 : _a[props.provider];
    const getValidationClass = (name) => {
        if (formMethods.formState.errors) {
            if (formMethods.formState.errors[name]) {
                return 'error';
            }
            else {
                return 'success';
            }
        }
    };
    const onSubmit = (fields) => __awaiter(void 0, void 0, void 0, function* () {
        var _a;
        setIsLoading(true);
        setErrorMessage('');
        try {
            const hotelId = hotel === null || hotel === void 0 ? void 0 : hotel.hotelID;
            const member = yield BookingAPI_1.default.Member.verifyMember(hotelId, props.provider, fields);
            if (member && member.memberId) {
                yield signUserIn({
                    saveState: true, //TODO: why was this false???
                    memberNumber: member.memberId,
                    memberProvider: props.provider,
                    firstName: fields.firstName,
                    lastName: fields.lastName,
                    email: fields.email,
                });
                // Preset checkout defaults
                (_a = basketContext.currentBasketRows) === null || _a === void 0 ? void 0 : _a.forEach((row) => (row.checkoutDefaults = {
                    firstName: fields.firstName,
                    lastName: fields.lastName,
                    email: fields.email,
                }));
            }
            else {
                setErrorMessage(t(Translation_1.Translation.ExternalMemberPopup.InvalidMember));
            }
        }
        catch (e) {
            if (e[(0, core_1.nameof)('Message')]) {
                setErrorMessage(e.Message);
            }
            else {
                throw e;
            }
        }
        finally {
            setIsLoading(false);
        }
    });
    return (react_1.default.createElement(SimpleModal_1.default, { open: props.isOpen, onClose: closeMemberSignupModal, size: SimpleModal_1.SimpleModalSize.Normal, alignCenter: true },
        react_1.default.createElement("div", { className: (0, classnames_1.default)(ExternalMemberModal_module_scss_1.default['external-member-modal'], 'row', `external-member-modal-${props.provider}`) },
            react_1.default.createElement("div", { className: "col-md-6 external-member-modal-image" },
                react_1.default.createElement("img", { src: ImageProvider_1.default.resizeImage(props.image, ImageProvider_1.ImageSize.Original), alt: props.title, className: ExternalMemberModal_module_scss_1.default['external-member-image'], style: { objectFit: props.imageSize } })),
            react_1.default.createElement("div", { className: "col-md-6 u-pad--heavy external-member-modal-content" },
                react_1.default.createElement("div", { className: "u-pad" },
                    react_1.default.createElement(Headline_1.default, { className: "external-member-modal-title", bold: true, color: modalPrimaryColor }, props.title),
                    props.subTitle && react_1.default.createElement(Text_1.default, { className: "u-marg-top external-member-modal-sub-title" }, props.subTitle),
                    react_1.default.createElement("form", { onSubmit: formMethods.handleSubmit(onSubmit) },
                        props.fields.map((field) => {
                            const isRequired = field.required !== false; // Default to true if not specified
                            const inputProps = Object.assign({ iconProps: { color: Color_1.Color.DarkGrey }, icon: field.icon, inputProps: { disabled: isLoading }, placeholder: field.label, wide: true, required: isRequired, validationStatus: getValidationClass(field.name) }, formMethods.register(field.name, { required: isRequired }));
                            return (react_1.default.createElement("div", { className: "u-marg-top u-marg-bottom", key: field.name },
                                react_1.default.createElement(InputGroup_1.default, { dimensions: "1" }, field.isMasked ? react_1.default.createElement(PasswordBox_1.PasswordBox, Object.assign({}, inputProps)) : react_1.default.createElement(TextBox_1.default, Object.assign({}, inputProps))),
                                field.helperText && (react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, color: Color_1.Color.DarkGrey }, field.helperText))));
                        }),
                        react_1.default.createElement(BEButton_1.default, { isLoading: isLoading, htmlType: "submit", className: "u-marg-top external-member-modal-submit-btn", size: "normal", filled: true, primary: hotel === null || hotel === void 0 ? void 0 : hotel.memberOnlyModalUsePrimaryColor, success: !(hotel === null || hotel === void 0 ? void 0 : hotel.memberOnlyModalUsePrimaryColor), stopIconAnimation: true, icon: Icon_1.IconType.ArrowRight, iconPosition: "right", wide: true }, t(Translation_1.Translation.ExternalMemberPopup.Submit)),
                        react_1.default.createElement("div", { className: "u-marg-top" },
                            react_1.default.createElement(Text_1.default, { bold: true, color: Color_1.Color.Danger }, errorMessage))),
                    memberOnlySignupLink && (react_1.default.createElement("div", { className: "external-member-modal-signup" },
                        react_1.default.createElement("div", { className: "line-break" }),
                        react_1.default.createElement("div", { className: "u-marg-top u-flex align-items-center u-justify-between" },
                            react_1.default.createElement(Text_1.default, { type: Text_1.TextType.Small, className: "u-flex align-items-center", color: Color_1.Color.DarkGrey }, t(Translation_1.Translation.ExternalMemberPopup.DontHaveAccount)),
                            react_1.default.createElement(BEButton_1.default, { className: "external-member-modal-signup-btn", htmlType: "button", size: "normal", filled: true, primary: true, onClick: () => window.open(memberOnlySignupLink, '_blank') }, t(Translation_1.Translation.ExternalMemberPopup.SignUp))))))))));
};
exports.default = ExternalMemberModal;
//# sourceMappingURL=ExternalMemberModal.js.map