"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StepConfirmationVGSPaymentInput = void 0;
const hooks_1 = require("../../../../hooks/index.js");
const react_1 = __importStar(require("react"));
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 Icon_1 = require("../../../generic/Icon/Icon");
const InputGroup_1 = __importDefault(require("../../../generic/InputGroup/InputGroup"));
const Text_1 = __importStar(require("../../../generic/Text"));
const AcceptablePaymentCard_1 = __importDefault(require("./AcceptablePaymentCard"));
const VGSHooks_1 = require("../../../../hooks/VGSHooks");
const HotelDTO_1 = require("../../../../models/Api/HotelDTO");
exports.StepConfirmationVGSPaymentInput = (0, react_1.forwardRef)(function ForwardedStepConfirmationVGSPaymentInput(props, ref) {
    var _a;
    const { hotel } = (0, hooks_1.useCurrentHotel)();
    const [errors, setErrors] = (0, react_1.useState)({});
    const { t } = (0, react_i18next_1.useTranslation)();
    const { focusElement } = (0, hooks_1.useWindowScroll)();
    const vgsInputCss = {
        fontSize: '13px',
        lineHeight: '18px',
        '&::placeholder': {
            color: '#8B8F9A',
            opacity: 1,
        },
    };
    const { fields: [cardNumber, nameOnCard, expirationDate, securityCode], vgsForm, } = (0, VGSHooks_1.useVgsCollect)([
        {
            label: t(Translation_1.Translation.Step.Confirmation.Inputs.CardNumber),
            name: 'credit-card',
            type: 'card-number',
            vgsProps: {
                autoComplete: ['cc-number'],
                successColor: '#4F8A10',
                errorColor: '#D8000C',
                showCardIcon: false,
                placeholder: t(Translation_1.Translation.Step.Confirmation.Inputs.CardNumber) + ' *',
                validations: ['required', 'validCardNumber'],
                css: vgsInputCss,
            },
        },
        {
            label: t(Translation_1.Translation.Step.Confirmation.Inputs.NameOnCard),
            name: 'card-name',
            type: 'text',
            vgsProps: {
                validations: ['required'],
                css: vgsInputCss,
                placeholder: t(Translation_1.Translation.Step.Confirmation.Inputs.NameOnCard) + ' *',
            },
        },
        {
            label: t(Translation_1.Translation.Step.Confirmation.Inputs.CardExpiry),
            name: 'expiration-date',
            type: 'card-expiration-date',
            vgsProps: {
                placeholder: t(Translation_1.Translation.Step.Confirmation.Inputs.CardExpiry) + ' *',
                validations: ['required', 'validCardExpirationDate'],
                css: vgsInputCss,
            },
        },
        {
            label: t(Translation_1.Translation.Step.Confirmation.Inputs.SecurityCode),
            name: 'security-code',
            type: 'card-security-code',
            vgsProps: {
                placeholder: t(Translation_1.Translation.Step.Confirmation.Inputs.SecurityCode) + ' *',
                validations: ['required', 'validCardSecurityCode'],
                css: vgsInputCss,
            },
        },
    ]);
    const setErrorsOnFaults = (faults) => {
        const newErrors = {};
        Object.keys(faults).forEach((input) => {
            let name = '';
            switch (input) {
                case 'credit-card':
                    name = t(Translation_1.Translation.Step.Confirmation.Inputs.CardNumber);
                    break;
                case 'expiration-date':
                    name = t(Translation_1.Translation.Step.Confirmation.Inputs.CardExpiry);
                    break;
                case 'security-code':
                    name = t(Translation_1.Translation.Step.Confirmation.Inputs.SecurityCode);
                    break;
                default:
                    name = t(Translation_1.Translation.Step.Confirmation.Inputs.NameOnCard);
                    break;
            }
            newErrors[input] = name + ' ' + faults[input].errorMessages[faults[input].errorMessages.length - 1];
        });
        setErrors(newErrors);
    };
    (0, react_1.useEffect)(() => {
        var _a, _b;
        if (errors && Object.keys(errors).length !== 0 && ((_a = cardNumber === null || cardNumber === void 0 ? void 0 : cardNumber.ref) === null || _a === void 0 ? void 0 : _a.current)) {
            focusElement((_b = cardNumber === null || cardNumber === void 0 ? void 0 : cardNumber.ref) === null || _b === void 0 ? void 0 : _b.current);
        }
    }, [errors]);
    (0, react_1.useImperativeHandle)(ref, () => ({
        submitPayment: () => new Promise((resolve, reject) => {
            if (vgsForm) {
                vgsForm.submit('/post', {
                    serializer: 'deep',
                    methods: 'POST',
                }, (status, response) => {
                    const cardData = response;
                    const expMatch = cardData['expiration-date'].match(/^(\d+)\s*\/\s*(\d+)$/);
                    if (!expMatch || expMatch[1].length > 2 || (expMatch[2].length !== 4 && expMatch[2].length !== 2)) {
                        setErrorsOnFaults({
                            'expiration-date': {
                                errorMessages: [t(Translation_1.Translation.Step.Confirmation.InputErrors.CardExpiry.Invalid)],
                            },
                        });
                        reject(t(Translation_1.Translation.Step.Confirmation.InputErrors.CardExpiry.Invalid));
                        return;
                    }
                    const expiration = (expMatch[1].length === 1 ? '0' : '') + expMatch[1] + (expMatch[2].length === 2 ? expMatch[2] : expMatch[2].substr(2));
                    const card = {
                        CVV: cardData['security-code'],
                        Expiry: expiration,
                        Name: cardData['card-name'],
                        Number: cardData['credit-card'],
                        Type: cardNumber.state.cardType,
                    };
                    resolve({
                        success: true,
                        message: 'Payment successful',
                        data: { PaymentCard: card },
                    });
                }, (error) => {
                    setErrorsOnFaults(error);
                    reject(error);
                });
            }
            else {
                console.error('VGS not on element, problem has occurred');
            }
        }),
    }));
    const formRef = (0, react_1.useRef)(null);
    const inputNames = ['credit-card', 'card-name', 'expiration-date', 'security-code'];
    const cardTypes = ((_a = hotel === null || hotel === void 0 ? void 0 : hotel.paymentCardTypes) !== null && _a !== void 0 ? _a : [])
        .map((card) => {
        const mapping = HotelDTO_1.SynxisToVGSCardNameMapping[card];
        if (!mapping) {
            return null;
        }
        return {
            name: HotelDTO_1.SynxisToVGSCardNameMapping[card],
            status: false,
        };
    })
        .filter((obj) => obj);
    return (react_1.default.createElement("div", null,
        inputNames.map((name) => {
            const errorMessage = errors[name];
            return (react_1.default.createElement(AutoAutoHeight_1.default, { open: !!errorMessage, key: name },
                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 }, errorMessage)))));
        }),
        react_1.default.createElement("div", { className: "u-marg-bottom" },
            react_1.default.createElement(AcceptablePaymentCard_1.default, { isCurrent: (cardKey) => {
                    var _a;
                    return cardNumber.state.cardType !== null && ((_a = cardTypes[cardKey]) === null || _a === void 0 ? void 0 : _a.name) === cardNumber.state.cardType;
                }, isDefault: (cardKey) => {
                    return cardNumber.state.cardType === null;
                } })),
        react_1.default.createElement("form", { ref: formRef },
            react_1.default.createElement(InputGroup_1.default, { dimensions: "2/2" },
                react_1.default.createElement("div", { className: cardNumber.getClasses(), ref: cardNumber.ref }),
                react_1.default.createElement(InputGroup_1.default, { dimensions: "2/2" },
                    react_1.default.createElement("div", { className: expirationDate.getClasses(), ref: expirationDate.ref }),
                    react_1.default.createElement("div", { className: securityCode.getClasses(), ref: securityCode.ref }))),
            react_1.default.createElement(InputGroup_1.default, { dimensions: "1" },
                react_1.default.createElement("div", { className: nameOnCard.getClasses(), ref: nameOnCard.ref })))));
});
//# sourceMappingURL=StepConfirmationPaymentDetails.js.map