"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.PaymentCardInput = void 0;
const react_1 = __importStar(require("react"));
const react_i18next_1 = require("react-i18next");
const AutoAutoHeight_1 = __importDefault(require("../../../animations/AutoAutoHeight"));
const Alert_1 = __importStar(require("../Alert"));
const Icon_1 = require("../Icon/Icon");
const InputGroup_1 = __importDefault(require("../InputGroup/InputGroup"));
const CardTypeSelect_1 = require("./CardTypeSelect");
const PaymentCard_1 = require("./PaymentCard");
const Text_1 = __importStar(require("../Text"));
const LoggedInUserHook_1 = require("../../../hooks/LoggedInUserHook");
const VGSHooks_1 = require("../../../hooks/VGSHooks");
const Translation_1 = require("../../../translations/Translation");
const AsyncAuth_1 = require("../../../util/AsyncAuth");
const Color_1 = require("../../../util/Color");
const Fade_1 = __importDefault(require("../../../animations/Fade"));
const BEButton_1 = __importDefault(require("../BEButton"));
const PaymentCardInput_module_scss_1 = __importDefault(require("./PaymentCardInput.module.scss"));
const PaymentCardInput = ({ card, onSubmit, onDeleteClicked, onMarkedAsDefaultClicked }) => {
    var _a, _b;
    const { user, fullName } = (0, LoggedInUserHook_1.useMember)();
    const { t } = (0, react_i18next_1.useTranslation)();
    const [errors, setErrors] = (0, react_1.useState)({});
    const [cardType, setCardType] = (0, react_1.useState)(null);
    const [isSavingVGSDetails, setIsSavingVGSDetails] = (0, react_1.useState)(false);
    const [isDeletingCard, setIsDeletingCard] = (0, react_1.useState)(false);
    const [isMarkingAsDefault, setIsMarkingAsDefault] = (0, react_1.useState)(false);
    const isCardDefault = (user === null || user === void 0 ? void 0 : user.defaultCard) === (card === null || card === void 0 ? void 0 : card.cardId);
    const inputsDisabled = !!(card === null || card === void 0 ? void 0 : card.cardId);
    const formatExpiry = (expiry) => {
        if (!/^\d{4}$/.test(expiry)) {
            return '••/••';
        }
        const month = expiry.slice(0, 2);
        const year = expiry.slice(2);
        return `${month}/${year}`;
    };
    const last4Digits = (_a = card === null || card === void 0 ? void 0 : card.cardNumber) === null || _a === void 0 ? void 0 : _a.substring(((_b = card === null || card === void 0 ? void 0 : card.cardNumber) === null || _b === void 0 ? void 0 : _b.length) - 4);
    const css = {
        fontSize: '13px',
        lineHeight: '18px',
        '&::placeholder': {
            color: '#8B8F9A',
            opacity: 1,
        },
    };
    const { fields: [cardNumber, cardHolder, expiryDate, securityCode], triggerFieldUpdate, vgsForm, } = (0, VGSHooks_1.useVgsCollect)([
        {
            name: 'credit-card',
            label: t(Translation_1.Translation.Step.Confirmation.Inputs.CardNumber),
            type: 'card-number',
            vgsProps: {
                validations: ['required', 'validCardNumber'],
                css,
                autoComplete: ['cc-number'],
                successColor: '#4F8A10',
                errorColor: '#D8000C',
                showCardIcon: false,
                placeholder: inputsDisabled ? `•••• •••• •••• ${last4Digits}` : '5913 2207 9578 4291',
                disabled: inputsDisabled,
            },
        },
        {
            name: 'card-name',
            label: t(Translation_1.Translation.Step.Confirmation.Inputs.NameOnCard),
            type: 'text',
            vgsProps: {
                validations: ['required'],
                css,
                disabled: inputsDisabled,
                placeholder: inputsDisabled ? '—' : fullName,
            },
        },
        {
            name: 'expiration-date',
            label: t(Translation_1.Translation.Step.Confirmation.Inputs.CardExpiry),
            type: 'card-expiration-date',
            vgsProps: {
                validations: ['required', 'validCardExpirationDate'],
                css,
                disabled: inputsDisabled,
                placeholder: inputsDisabled ? formatExpiry(card.expiry) : '12/27',
            },
        },
        {
            name: 'security-code',
            label: t(Translation_1.Translation.Step.Confirmation.Inputs.SecurityCode),
            type: 'card-security-code',
            vgsProps: {
                validations: ['required', 'validCardSecurityCode'],
                css,
                disabled: inputsDisabled,
                placeholder: inputsDisabled ? '•••' : '552',
            },
        },
    ], 'members');
    (0, react_1.useEffect)(() => {
        triggerFieldUpdate();
    }, [card]);
    (0, react_1.useEffect)(() => {
        if (cardNumber === null || cardNumber === void 0 ? void 0 : cardNumber.state.cardType) {
            setCardType(cardNumber.state.cardType);
        }
    }, [cardNumber]);
    const inputNames = ['credit-card', 'card-name', 'expiration-date', 'security-code'];
    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);
    };
    const onChangeSubmit = () => __awaiter(void 0, void 0, void 0, function* () {
        const Auth = yield (0, AsyncAuth_1.getAuth)();
        if (vgsForm) {
            setIsSavingVGSDetails(true);
            Auth.currentAuthenticatedUser().then((cognitoData) => {
                const jwtToken = cognitoData.signInUserSession.idToken.jwtToken;
                vgsForm.submit('/members/vgs-hide', {
                    serializer: 'deep',
                    methods: 'POST',
                    headers: {
                        Authorization: jwtToken,
                    },
                }, (status, cardData) => __awaiter(void 0, void 0, void 0, function* () {
                    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)],
                            },
                        });
                        return;
                    }
                    const expiration = (expMatch[1].length === 1 ? '0' : '') + expMatch[1] + (expMatch[2].length === 2 ? expMatch[2] : expMatch[2].substr(2));
                    const newCard = {
                        username: card.username,
                        cardId: card.cardId,
                        securityCode: cardData['security-code'],
                        expiry: expiration,
                        name: cardData['card-name'],
                        cardNumber: cardData['credit-card'],
                        type: cardType,
                    };
                    const newAddedCard = yield (onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(newCard));
                    onMarkAsDefault(newAddedCard);
                    vgsForm.reset();
                    setIsSavingVGSDetails(false);
                }), (error) => {
                    setErrorsOnFaults(error);
                    setIsSavingVGSDetails(false);
                });
            });
        }
        else {
            console.error('VGS not on element, problem has occurred');
        }
    });
    const onDeleteCardClicked = () => {
        setIsDeletingCard(true);
        onDeleteClicked === null || onDeleteClicked === void 0 ? void 0 : onDeleteClicked(card).finally(() => {
            setIsDeletingCard(false);
        });
    };
    const onMarkAsDefault = (newCard) => {
        setIsMarkingAsDefault(true);
        onMarkedAsDefaultClicked === null || onMarkedAsDefaultClicked === void 0 ? void 0 : onMarkedAsDefaultClicked(newCard).finally(() => {
            setIsMarkingAsDefault(false);
        });
    };
    const onMarkAsDefaultClicked = () => {
        onMarkAsDefault(card);
    };
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { className: PaymentCardInput_module_scss_1.default['card-inputs'] },
            react_1.default.createElement("div", { className: "u-marg-bottom--medium u-marg-top--heavy@l-" },
                react_1.default.createElement(CardTypeSelect_1.CardTypeSelect, { value: cardType || undefined })),
            react_1.default.createElement("div", { className: "u-margin-bottom" }, 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("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.Step.Confirmation.Inputs.CardNumber))),
                react_1.default.createElement("div", { className: cardNumber.getClasses(), ref: cardNumber.ref })),
            react_1.default.createElement("div", { className: "u-marg-bottom" },
                react_1.default.createElement(InputGroup_1.default, { dimensions: "2/2" },
                    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.Step.Confirmation.Inputs.CardExpiry))),
                        react_1.default.createElement("div", { className: expiryDate.getClasses(), ref: expiryDate.ref })),
                    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.Step.Confirmation.Inputs.SecurityCode))),
                        react_1.default.createElement("div", { className: securityCode.getClasses(), ref: securityCode.ref })))),
            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.Step.Confirmation.Inputs.NameOnCard))),
                react_1.default.createElement("div", { className: cardHolder.getClasses(), ref: cardHolder.ref })),
            react_1.default.createElement("div", { className: "u-marg-bottom" }, (card === null || card === void 0 ? void 0 : card.cardId) ? (react_1.default.createElement(BEButton_1.default, { className: "u-marg-top--heavier@l u-marg-top--heavy@l- u-flex u-flex-justify-center", isLoading: isDeletingCard, textColor: Color_1.Color.Danger, isText: true, icon: Icon_1.IconType.Delete, onClick: onDeleteCardClicked, stopIconAnimation: true }, t(Translation_1.Translation.UserPortal.PaymentInformationScreen.DeleteCard))) : (react_1.default.createElement(BEButton_1.default, { className: "u-marg-top--heavier@l u-marg-top--heavy@l- u-flex u-flex-justify-center", isLoading: isSavingVGSDetails, rounded: true, primary: true, filled: true, mobileWidth: true, onClick: onChangeSubmit }, t(Translation_1.Translation.UserPortal.PaymentInformationScreen.SaveCard))))),
        react_1.default.createElement(Fade_1.default, { open: !!(card === null || card === void 0 ? void 0 : card.cardId) },
            react_1.default.createElement("div", { className: PaymentCardInput_module_scss_1.default['card-large'] },
                react_1.default.createElement(PaymentCard_1.PaymentCard, { card: card }),
                react_1.default.createElement("div", { className: "u-marg-top u-marg-top--heavy@l-" },
                    react_1.default.createElement(BEButton_1.default, { onClick: onMarkAsDefaultClicked, isLoading: isMarkingAsDefault, disabled: isCardDefault, filled: true, primary: true, size: "small" }, "Mark as Default"))))));
};
exports.PaymentCardInput = PaymentCardInput;
//# sourceMappingURL=PaymentCardInput.js.map