"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FormStripe = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _FormStripe = require("./FormStripe.l10n");
var style = _interopRequireWildcard(require("./FormStripe.module.css"));
var _herlpes = require("./herlpes");
var _loadScript = require("../../../../../helpers/loadScript");
var _helpers = require("../../../../helpers");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
const AUTO = 'auto';
const CARD = 'card';
const DEFAULT_BILLING_DETAILS = {
  address: {
    country: 'never'
  },
  name: 'never'
};
let checkout;
const FormStripe = _ref => {
  let publicKey = _ref.publicKey,
    response = _ref.response;
  const _useLocale = (0, _locale.useLocale)(),
    translate = _useLocale.translate;
  const _useState = (0, _react.useState)(),
    _useState2 = _slicedToArray(_useState, 2),
    busy = _useState2[0],
    setBusy = _useState2[1];
  const _useState3 = (0, _react.useState)(),
    _useState4 = _slicedToArray(_useState3, 2),
    country = _useState4[0],
    setCountry = _useState4[1];
  const _useState5 = (0, _react.useState)(),
    _useState6 = _slicedToArray(_useState5, 2),
    name = _useState6[0],
    setName = _useState6[1];
  const _useState7 = (0, _react.useState)(),
    _useState8 = _slicedToArray(_useState7, 2),
    nameError = _useState8[0],
    setNameError = _useState8[1];
  const _useState9 = (0, _react.useState)(),
    _useState0 = _slicedToArray(_useState9, 2),
    ready = _useState0[0],
    setReady = _useState0[1];
  const _useState1 = (0, _react.useState)(),
    _useState10 = _slicedToArray(_useState1, 2),
    stripeReady = _useState10[0],
    setStripeReady = _useState10[1];
  const _useState11 = (0, _react.useState)(),
    _useState12 = _slicedToArray(_useState11, 2),
    type = _useState12[0],
    setType = _useState12[1];
  const refAdaptivePricing = (0, _react.useRef)();
  const refElements = (0, _react.useRef)();
  (0, _react.useEffect)(() => {
    const domain = 'payments';
    const id = 'stripeScript';
    (async () => {
      await (0, _loadScript.loadScript)({
        async: false,
        domain,
        id,
        src: "https://js.stripe.com/dahlia/stripe.js",
        onLoad: handleLoad
      });
    })();
    return () => {
      const el = document.getElementById("".concat(domain, "-").concat(id));
      el && el.parentNode.removeChild(el);
    };
  }, [response]);
  (0, _react.useEffect)(() => {
    if (!response || !ready) return;
    setBusy();
    setStripeReady();
    const _response$configurati = response.configuration,
      _response$configurati2 = _response$configurati === void 0 ? {} : _response$configurati,
      adaptivePricing = _response$configurati2.adaptivePricing,
      cardHolderName = _response$configurati2.cardHolderName,
      clientCountry = _response$configurati2.clientCountry,
      clientSecret = _response$configurati2.clientSecret,
      stripeAccount = _response$configurati2.stripeAccountId;
    setCountry(clientCountry);
    if (cardHolderName) setName(cardHolderName);
    (async () => {
      checkout = window.Stripe(publicKey, {
        stripeAccount
      }).initCheckoutElementsSdk({
        adaptivePricing,
        clientSecret,
        elementsOptions: {
          appearance: {
            theme: 'stripe',
            variables: (0, _herlpes.getStyle)()
          }
        }
      });
      checkout.loadFonts([{
        cssSrc: 'https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&display=swap'
      }]);
      const paymentElement = checkout.createPaymentElement({
        layout: 'tabs',
        fields: {
          billingDetails: clientCountry ? DEFAULT_BILLING_DETAILS : AUTO
        }
      });
      paymentElement.on('ready', () => {
        setStripeReady(true);
      });
      paymentElement.on('change', event => {
        const _event$value = event.value,
          value = _event$value === void 0 ? {} : _event$value;
        setType(value.type);
        checkout.getPaymentElement().update({
          fields: {
            billingDetails: value.type === CARD && clientCountry ? DEFAULT_BILLING_DETAILS : AUTO
          }
        });
      });
      if (adaptivePricing !== null && adaptivePricing !== void 0 && adaptivePricing.allowed) checkout.createCurrencySelectorElement().mount(refAdaptivePricing.current);
      paymentElement.mount(refElements.current);
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ready, response]);
  const handleNameChange = value => {
    if (value) setNameError();
    setName(value);
  };
  const handleLoad = async () => {
    setReady(true);
  };
  const handlePress = async () => {
    if (!checkout) return;
    setBusy(true);
    const loadActionsResult = await checkout.loadActions();
    if (loadActionsResult.type === 'success') {
      const session = await loadActionsResult.actions.getSession();
      if (!name && type === CARD && country) {
        setNameError(true);
        if (session.canConfirm) return setBusy(false);
      }
      const _await$loadActionsRes = await loadActionsResult.actions.confirm(name ? {
          billingAddress: {
            name,
            address: {
              country
            }
          }
        } : undefined),
        error = _await$loadActionsRes.error;
      if (session.canConfirm && error) {
        _dataSources.Event.publish(_helpers.EVENT.NOTIFICATION, {
          error: true,
          defaultMessage: translate(_FormStripe.L10N.NOTIFICATION_ERROR)
        });
      }
    }
    setBusy(false);
  };
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ui.Progress, {
    indeterminate: true,
    visible: !stripeReady
  }), /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.container
  }, /*#__PURE__*/_react.default.createElement(_ui.View, {
    ref: refAdaptivePricing
  }), /*#__PURE__*/_react.default.createElement(_ui.View, {
    ref: refElements
  }), type === CARD && country && /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.form
  }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    action: true,
    "label-for": "name"
  }, translate(_FormStripe.L10N.LABEL_CARD_NAME)), /*#__PURE__*/_react.default.createElement(_ui.Input, {
    name: "name",
    value: name,
    onChange: handleNameChange,
    className: (0, _ui.styles)(style.name, nameError && style.error)
  }), nameError && /*#__PURE__*/_react.default.createElement(_ui.Text, {
    action: true,
    error: true
  }, translate(_FormStripe.L10N.LABEL_CARD_NAME_ERROR)))), !!stripeReady && /*#__PURE__*/_react.default.createElement(_ui.Button, {
    busy: busy,
    onPress: handlePress,
    className: style.button
  }, translate(_FormStripe.L10N.ACTION_PAY)));
};
exports.FormStripe = FormStripe;
FormStripe.displayName = 'Mirai:Payments:ButtonPayment:FormStripe';
FormStripe.propTypes = {
  publicKey: _propTypes.default.string.isRequired,
  response: _propTypes.default.object
};
//# sourceMappingURL=FormStripe.js.map