"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 }; }
const AUTO = 'auto';
const CARD = 'card';
const DEFAULT_BILLING_DETAILS = {
  address: {
    country: 'never'
  },
  name: 'never'
};
let checkout;
const FormStripe = _ref => {
  let {
    publicKey,
    response
  } = _ref;
  const {
    translate
  } = (0, _locale.useLocale)();
  const [busy, setBusy] = (0, _react.useState)();
  const [country, setCountry] = (0, _react.useState)();
  const [name, setName] = (0, _react.useState)();
  const [nameError, setNameError] = (0, _react.useState)();
  const [ready, setReady] = (0, _react.useState)();
  const [stripeReady, setStripeReady] = (0, _react.useState)();
  const [type, setType] = (0, _react.useState)();
  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/clover/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 {
      configuration: {
        clientCountry,
        clientSecret,
        stripeAccountId: stripeAccount
      } = {}
    } = response;
    setCountry(clientCountry);
    (async () => {
      checkout = window.Stripe(publicKey, {
        stripeAccount
      }).initCheckout({
        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 {
          value = {}
        } = event;
        setType(value.type);
        checkout.getPaymentElement().update({
          fields: {
            billingDetails: value.type === CARD && clientCountry ? DEFAULT_BILLING_DETAILS : AUTO
          }
        });
      });
      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 {
        error
      } = await loadActionsResult.actions.confirm(name ? {
        billingAddress: {
          name,
          address: {
            country
          }
        }
      } : undefined);
      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: 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