"use strict";
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
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 __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));
var react_stripe_elements_1 = require("react-stripe-elements");
var styled_components_1 = __importDefault(require("styled-components"));
var PaymentsFormWrapper_1 = require("./PaymentsFormWrapper");
var elements_1 = require("@joincivil/elements");
var context_1 = require("../context");
var utils_1 = require("@joincivil/utils");
var PaymentsStyledComponents_1 = require("./PaymentsStyledComponents");
var PaymentsTextComponents_1 = require("./PaymentsTextComponents");
var PaymentsInputValidationUI_1 = require("./PaymentsInputValidationUI");
var types_1 = require("./types");
var StripeWrapper = styled_components_1.default.div(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n  margin: 20px 0 0;\n  max-width: 500px;\n  width: 100%;\n"], ["\n  margin: 20px 0 0;\n  max-width: 500px;\n  width: 100%;\n"])));
var StripeCardInfoFlex = styled_components_1.default.div(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n  display: flex;\n\n  & > div {\n    width: 50%;\n  }\n"], ["\n  display: flex;\n\n  & > div {\n    width: 50%;\n  }\n"])));
var CreditCardIconsWrap = styled_components_1.default.div(templateObject_3 || (templateObject_3 = __makeTemplateObject(["\n  position: absolute;\n  right: ", ";\n  top: 13px;\n\n  svg {\n    margin-right: 8px;\n  }\n\n  ", " {\n    right: ", ";\n\n    svg {\n      margin-right: 5px;\n    }\n  }\n"], ["\n  position: absolute;\n  right: ", ";\n  top: 13px;\n\n  svg {\n    margin-right: 8px;\n  }\n\n  ", " {\n    right: ", ";\n\n    svg {\n      margin-right: 5px;\n    }\n  }\n"])), function (props) { return (props.inputState === types_1.INPUT_STATE.INVALID ? "30px" : "10px"); }, elements_1.mediaQueries.MOBILE, function (props) { return (props.inputState === types_1.INPUT_STATE.INVALID ? "25px" : "8px"); });
var CreditCardCVCWrap = styled_components_1.default.div(templateObject_4 || (templateObject_4 = __makeTemplateObject(["\n  position: absolute;\n  right: ", ";\n  top: 10px;\n"], ["\n  position: absolute;\n  right: ", ";\n  top: 10px;\n"])), function (props) { return (props.inputState === types_1.INPUT_STATE.INVALID ? "30px" : "10px"); });
var DropDownWrap = styled_components_1.default.div(templateObject_5 || (templateObject_5 = __makeTemplateObject(["\n  position: absolute;\n  right: 10px;\n  top: 8px;\n  z-index: 0;\n"], ["\n  position: absolute;\n  right: 10px;\n  top: 8px;\n  z-index: 0;\n"])));
var PaymentStripeForm = /** @class */ (function (_super) {
    __extends(PaymentStripeForm, _super);
    function PaymentStripeForm(props) {
        var _this = _super.call(this, props) || this;
        _this.handleOnBlur = function (event) {
            var state = event.target.id;
            var value = event.target.value;
            switch (state) {
                case "email":
                    var validEmail = utils_1.isValidEmail(value);
                    validEmail
                        ? _this.setState({ email: value, emailState: types_1.INPUT_STATE.VALID })
                        : _this.setState({ emailState: types_1.INPUT_STATE.INVALID });
                    break;
                case "name":
                    var validName = value !== "";
                    validName
                        ? _this.setState({ name: value, nameState: types_1.INPUT_STATE.VALID })
                        : _this.setState({ nameState: types_1.INPUT_STATE.INVALID });
                    break;
                case "zip":
                    var validPostalCode = _this.isValidPostalCode(value);
                    validPostalCode
                        ? _this.setState({ postalCode: value, postalCodeState: types_1.INPUT_STATE.VALID })
                        : _this.setState({ postalCodeState: types_1.INPUT_STATE.INVALID });
                    break;
                default:
                    break;
            }
        };
        _this.isValidPostalCode = function (inputPostalCode) {
            var postalCode = inputPostalCode.toString().trim();
            var usa = /^[0-9]{5}(?:-[0-9]{4})?$/;
            var can = /^[ABCEGHJKLMNPRSTVXY]\d[ -]?\d[A-Za-z]\d$/;
            var gbr = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i;
            // Stripe recommends getting the zip/postal codes for the US, UK, and Canada
            switch (_this.state.country) {
                case "USA":
                    return usa.test(postalCode);
                case "CAN":
                    return can.test(postalCode);
                case "GBR":
                    return gbr.test(postalCode);
                default:
                    return true;
            }
        };
        _this.handleOnBlurStripe = function () {
            var stripeElements = document.querySelectorAll(".StripeElement");
            stripeElements.forEach(function (element) {
                var id = element.id;
                var classList = element.classList;
                if (classList.contains("StripeElement--invalid")) {
                    _this.isStripeElementValid(id, types_1.INPUT_STATE.INVALID);
                }
                else if (classList.contains("StripeElement--empty")) {
                    _this.isStripeElementValid(id, types_1.INPUT_STATE.EMPTY);
                }
                else {
                    _this.isStripeElementValid(id, types_1.INPUT_STATE.VALID);
                }
            });
        };
        _this.isStripeElementValid = function (element, state) {
            switch (element) {
                case "card-number":
                    _this.setState({ cardNumberState: state });
                    break;
                case "card-expiry":
                    _this.setState({ cardExpiryState: state });
                    break;
                case "card-cvc":
                    _this.setState({ cardCVCState: state });
                    break;
                default:
                    break;
            }
        };
        _this.state = {
            email: _this.props.userEmail || "",
            emailState: _this.props.userEmail ? types_1.INPUT_STATE.VALID : types_1.INPUT_STATE.EMPTY,
            name: "",
            nameState: types_1.INPUT_STATE.EMPTY,
            country: "USA",
            postalCode: "",
            postalCodeState: types_1.INPUT_STATE.VALID,
            cardNumberState: types_1.INPUT_STATE.EMPTY,
            cardExpiryState: types_1.INPUT_STATE.EMPTY,
            cardCVCState: types_1.INPUT_STATE.EMPTY,
            isPaymentError: false,
            paymentProcessing: false,
        };
        _this.handleSubmit = _this.handleSubmit.bind(_this);
        return _this;
    }
    PaymentStripeForm.prototype.render = function () {
        var _this = this;
        return (React.createElement(React.Fragment, null,
            React.createElement(PaymentsFormWrapper_1.PaymentsFormWrapper, { handleEditPaymentType: this.props.handleEditPaymentType, payWithText: React.createElement(PaymentsTextComponents_1.PayWithCardText, null), paymentNoticeText: React.createElement(PaymentsTextComponents_1.PaymentStripeNoticeText, null), showSecureIcon: true },
                React.createElement(StripeWrapper, null,
                    React.createElement(PaymentsStyledComponents_1.PaymentInputLabel, null, "Email"),
                    React.createElement(PaymentsInputValidationUI_1.InputValidationUI, { inputState: this.state.emailState },
                        React.createElement("input", { defaultValue: this.state.email, id: "email", name: "email", type: "email", maxLength: 254, onBlur: function () { return _this.handleOnBlur(event); } }),
                        React.createElement(PaymentsTextComponents_1.PaymentEmailConfirmationText, null)),
                    React.createElement(PaymentsStyledComponents_1.PaymentInputLabel, null, "Card information"),
                    React.createElement(PaymentsInputValidationUI_1.InputValidationUI, { inputState: this.state.cardNumberState, className: "positionTop" },
                        React.createElement(PaymentsInputValidationUI_1.StripeElement, { inputState: this.state.cardNumberState },
                            React.createElement(react_stripe_elements_1.CardNumberElement, { id: "card-number", style: { base: { fontSize: "13px" } }, onBlur: function () { return _this.handleOnBlurStripe(); } })),
                        React.createElement(CreditCardIconsWrap, { inputState: this.state.cardNumberState },
                            React.createElement(elements_1.CCAmexIcon, null),
                            React.createElement(elements_1.CCDiscoverIcon, null),
                            React.createElement(elements_1.CCMastercardIcon, null),
                            React.createElement(elements_1.CCVisaIcon, null))),
                    React.createElement(StripeCardInfoFlex, null,
                        React.createElement(PaymentsInputValidationUI_1.InputValidationUI, { inputState: this.state.cardExpiryState, className: "positionBottomLeft" },
                            React.createElement(PaymentsInputValidationUI_1.StripeElement, { inputState: this.state.cardExpiryState },
                                React.createElement(react_stripe_elements_1.CardExpiryElement, { id: "card-expiry", style: { base: { fontSize: "13px" } }, onBlur: function () { return _this.handleOnBlurStripe(); } }))),
                        React.createElement(PaymentsInputValidationUI_1.InputValidationUI, { inputState: this.state.cardCVCState, className: "positionBottomRight" },
                            React.createElement(PaymentsInputValidationUI_1.StripeElement, { inputState: this.state.cardCVCState },
                                React.createElement(react_stripe_elements_1.CardCvcElement, { id: "card-cvc", style: { base: { fontSize: "13px" } }, onBlur: function () { return _this.handleOnBlurStripe(); } })),
                            React.createElement(CreditCardCVCWrap, { inputState: this.state.cardCVCState },
                                React.createElement(elements_1.CCSecurityCodeIcon, null)))),
                    React.createElement(PaymentsStyledComponents_1.PaymentInputLabel, null, "Name on card"),
                    React.createElement(PaymentsInputValidationUI_1.InputValidationUI, { inputState: this.state.nameState },
                        React.createElement("input", { id: "name", name: "name", onBlur: function () { return _this.handleOnBlur(event); }, required: true })),
                    React.createElement(PaymentsStyledComponents_1.PaymentInputLabel, null, "Country or region"),
                    React.createElement(PaymentsInputValidationUI_1.InputValidationUI, { className: "positionTop" },
                        React.createElement("select", { id: "country", name: "country", onChange: function () { return _this.handleOnBlur(event); } }, utils_1.STRIPE_COUNTRIES.map(function (country, i) {
                            return (React.createElement("option", { key: i, value: country.value }, country.name));
                        })),
                        React.createElement(DropDownWrap, null,
                            React.createElement(elements_1.DropdownArrow, null))),
                    React.createElement(PaymentsInputValidationUI_1.InputValidationUI, { inputState: this.state.postalCodeState, className: "positionBottom" },
                        React.createElement("input", { id: "zip", name: "zip", maxLength: 12, placeholder: "Zip code", onBlur: function () { return _this.handleOnBlur(event); } })))),
            React.createElement(PaymentsStyledComponents_1.PaymentBtn, { onClick: function () { return _this.handleSubmit(); }, disabled: this.state.paymentProcessing }, this.state.paymentProcessing ? "Payment processing..." : "Complete Boost"),
            this.state.isPaymentError && (React.createElement(PaymentsStyledComponents_1.PaymentError, null,
                React.createElement(PaymentsTextComponents_1.PaymentErrorText, null))),
            React.createElement(PaymentsStyledComponents_1.PaymentTerms, null,
                React.createElement(PaymentsTextComponents_1.PaymentTermsText, null))));
    };
    PaymentStripeForm.prototype.handleSubmit = function () {
        return __awaiter(this, void 0, void 0, function () {
            var token, err_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.state.emailState === types_1.INPUT_STATE.VALID &&
                            this.state.nameState === types_1.INPUT_STATE.VALID &&
                            this.state.postalCodeState === types_1.INPUT_STATE.VALID &&
                            this.state.cardNumberState === types_1.INPUT_STATE.VALID &&
                            this.state.cardExpiryState === types_1.INPUT_STATE.VALID &&
                            this.state.cardCVCState === types_1.INPUT_STATE.VALID)) return [3 /*break*/, 5];
                        this.setState({ paymentProcessing: true, isPaymentError: false });
                        if (!this.props.stripe) return [3 /*break*/, 5];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 4, , 5]);
                        return [4 /*yield*/, this.props.stripe.createToken({
                                name: this.state.name,
                                address_country: this.state.country,
                                address_zip: this.state.postalCode,
                            })];
                    case 2:
                        token = _a.sent();
                        return [4 /*yield*/, this.props.savePayment({
                                variables: {
                                    postID: this.props.postId,
                                    input: {
                                        // @ts-ignore
                                        paymentToken: token.token.id,
                                        amount: this.props.usdToSpend,
                                        currencyCode: "usd",
                                        emailAddress: this.state.email,
                                        shouldPublicize: this.props.shouldPublicize,
                                        payerChannelID: this.props.userChannelID,
                                    },
                                },
                            })];
                    case 3:
                        _a.sent();
                        this.props.handlePaymentSuccess();
                        return [3 /*break*/, 5];
                    case 4:
                        err_1 = _a.sent();
                        console.error(err_1);
                        this.setState({ paymentProcessing: false, isPaymentError: true });
                        return [3 /*break*/, 5];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    PaymentStripeForm.contextType = context_1.CivilContext;
    return PaymentStripeForm;
}(React.Component));
exports.default = react_stripe_elements_1.injectStripe(PaymentStripeForm);
var templateObject_1, templateObject_2, templateObject_3, templateObject_4, templateObject_5;
//# sourceMappingURL=PaymentsStripeForm.js.map