"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Form = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _services = require("@mirai/services");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var _shared__ = require("../../__shared__");
var _helpers = require("../../helpers");
var _Checkout = require("../Checkout.constants");
var _Checkout2 = require("../Checkout.l10n");
var style = _interopRequireWildcard(require("../Checkout.module.css"));
var _helpers2 = require("../helpers");
const _excluded = ["currency", "repositories", "form", "tracking"],
  _excluded2 = ["children", "dataSource", "showErrors", "onError"];
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 _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
const storage = new _dataSources.Storage({
  adapter: _dataSources.LocalAdapter,
  cache: _Checkout.FORM_STORAGE_CACHE
});
const key = (dataSource, schema) => "".concat(_Checkout.FORM_STORAGE_KEY, ":").concat((0, _helpers.generateId)(JSON.stringify(_objectSpread(_objectSpread({}, dataSource), {}, {
  schema: Object.entries(schema).filter(_ref => {
    let [, value] = _ref;
    return value.input !== _Checkout.INPUT.HTML;
  }).map(_ref2 => {
    let [key] = _ref2;
    return key;
  })
}))));
const Form = _ref3 => {
  var _payment$config, _payment$config$publi, _payment$info, _payment$info2;
  let {
      children,
      dataSource: {
        currency,
        repositories: {
          countries
        } = {},
        form: schema = {},
        tracking = {}
      } = {},
      showErrors = false,
      onError = () => {}
    } = _ref3,
    dataSource = _objectWithoutProperties(_ref3.dataSource, _excluded),
    others = _objectWithoutProperties(_ref3, _excluded2);
  const {
    isDesktop
  } = (0, _ui.useDevice)();
  const {
    translate
  } = (0, _locale.useLocale)();
  const {
    set,
    value: {
      club,
      language,
      payment: storePayment,
      session
    } = {}
  } = (0, _dataSources.useStore)();
  const formReady = (0, _react.useRef)(false);
  const [errorForm, setErrorForm] = (0, _react.useState)({});
  const [errorPayment, setErrorPayment] = (0, _react.useState)({});
  const [form, setForm] = (0, _react.useState)(storage.get(key(dataSource, schema)) || Object.fromEntries(Object.entries(schema).map(_ref4 => {
    let [key, {
      value
    }] = _ref4;
    return [key, value];
  })));
  const [formTracked, setFormTracked] = (0, _react.useState)();
  const [modal, setModal] = (0, _react.useState)(false);
  (0, _react.useEffect)(() => {
    setForm(_objectSpread(_objectSpread({}, form), (0, _helpers2.getSchemaProps)({
      schema,
      value: session
    })));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [session]);
  (0, _react.useLayoutEffect)(() => {
    if (Object.keys(form).length) storage.set(key(dataSource, schema), form);
    set({
      checkout: form
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [form]);
  (0, _react.useEffect)(() => {
    onError(_objectSpread(_objectSpread({}, errorForm), errorPayment));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [errorForm, errorPayment]);
  (0, _react.useEffect)(() => {
    if (formReady.current) return;
    const hasRequiredValues = getFields(form).filter(_ref5 => {
      let [, field] = _ref5;
      return field.required;
    }).map(_ref6 => {
      let [key] = _ref6;
      return key;
    }).every(key => form[key] !== undefined && form[key] !== '');
    const hasErrors = Object.keys(errorForm).length > 0 || Object.keys(errorPayment).length > 0;
    if (!hasErrors && hasRequiredValues && Object.keys(storePayment || {}).length > 0) {
      _dataSources.Event.publish(_helpers.EVENT.METRICS, {
        id: _helpers.METRICS_EVENTS.CHECKOUT_INTERACTION,
        action: 'form_ready'
      });
      formReady.current = true;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [errorForm, errorPayment, storePayment]);
  const handleChange = async value => {
    const next = _objectSpread(_objectSpread({}, form), value);
    if (!!schema.country && next.country && !next.phone) {
      const {
        code
      } = await _services.ServiceCountry.info((0, _helpers.getCountryCode)(next.country, countries));
      if (code) next.phone = code;
    }
    const nextFields = getFields(next);
    const nextFiltered = nextFields.length < getFields(form).length ? Object.fromEntries(Object.entries(next).filter(_ref7 => {
      let [key] = _ref7;
      return Object.fromEntries(nextFields)[key] !== undefined;
    })) : undefined;
    setForm(nextFiltered || next);
  };
  const handleLeave = () => {
    const {
      email,
      firstName,
      lastName,
      phone
    } = errorForm;
    if (!formTracked && !email && !firstName && !lastName && !phone) {
      _dataSources.Event.publish(_helpers.EVENT.CHECKOUT_FORM, {
        event: _helpers.EVENT.CHECKOUT_FORM,
        response: {
          tracking
        }
      });
      setFormTracked(true);
    }
  };
  const handleFormError = errors => {
    setErrorForm(errors);
  };
  const getFields = value => Object.entries(schema).filter(_ref8 => {
    let [key] = _ref8;
    return !!schema[key];
  }).filter(_ref9 => {
    let [, {
      visible
    }] = _ref9;
    return !visible || visible(value);
  });
  const {
    payment
  } = dataSource || {};
  const {
    testId
  } = others;
  const formProps = _objectSpread(_objectSpread({}, others), {}, {
    autoComplete: 'off',
    showErrors,
    validateOnMount: true,
    onChange: handleChange,
    onError: handleFormError,
    onLeave: handleLeave,
    className: (0, _ui.styles)(style.form, style.box)
  });
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ui.Form, _extends({}, formProps, {
    testId: "".concat(testId, "-required")
  }), /*#__PURE__*/_react.default.createElement(_ui.Text, {
    bold: true,
    headline: isDesktop,
    wide: true
  }, translate(_Checkout2.L10N.LABEL_PERSONAL_DETAILS)), getFields(form).filter(_ref0 => {
    let [, field] = _ref0;
    return field.required;
  }).map(_ref1 => {
    let [key, field = {}] = _ref1;
    return /*#__PURE__*/_react.default.createElement(_Checkout.FIELD[field.input] || _ui.InputText, (0, _helpers2.getFieldProps)(key, field, _objectSpread({
      value: form[key],
      error: errorForm[key],
      language,
      session,
      translate
    }, dataSource), club, () => setModal(true)));
  })), children, payment && /*#__PURE__*/_react.default.createElement(_shared__.Payment, _extends({}, _objectSpread(_objectSpread({}, payment), {}, {
    config: _objectSpread(_objectSpread({}, payment.config), {}, {
      publicKey: (_payment$config = payment.config) === null || _payment$config === void 0 ? void 0 : (_payment$config$publi = _payment$config.publicKey) === null || _payment$config$publi === void 0 ? void 0 : _payment$config$publi[storePayment.method]
    }),
    info: _objectSpread(_objectSpread({}, payment.info), {}, {
      date: (_payment$info = payment.info) !== null && _payment$info !== void 0 && _payment$info.date ? (0, _locale.parseDate)((_payment$info2 = payment.info) === null || _payment$info2 === void 0 ? void 0 : _payment$info2.date) : undefined
    }),
    showErrors
  }), {
    currency: currency,
    requiredText: translate(_Checkout2.L10N.LABEL_REQUIRED),
    onError: setErrorPayment
  })), /*#__PURE__*/_react.default.createElement(_ui.Form, _extends({}, formProps, {
    testId: "".concat(testId, "-adittional")
  }), /*#__PURE__*/_react.default.createElement(_ui.Text, {
    bold: true,
    headline: isDesktop,
    wide: true
  }, translate(_Checkout2.L10N.LABEL_ADDITIONAL_INFO)), getFields(form).filter(_ref10 => {
    let [, field] = _ref10;
    return !field.required;
  }).map(_ref11 => {
    let [key, field = {}] = _ref11;
    return /*#__PURE__*/_react.default.createElement(_Checkout.FIELD[field.input] || _ui.InputText, (0, _helpers2.getFieldProps)(key, field, _objectSpread({
      value: form[key],
      error: errorForm[key],
      language,
      session,
      translate
    }, dataSource), club, () => setModal(true)));
  })), /*#__PURE__*/_react.default.createElement(_ui.Modal, {
    fit: true,
    title: translate(_Checkout2.L10N.LABEL_CONDITIONS),
    visible: modal,
    onClose: () => setModal(false),
    className: style.modal
  }, /*#__PURE__*/_react.default.createElement(_ui.ScrollView, {
    snap: false,
    vertical: true,
    className: style.scrollview
  }, /*#__PURE__*/_react.default.createElement(_shared__.BookingTerms, {
    dataSource: dataSource,
    small: true,
    className: style.others
  }))));
};
exports.Form = Form;
Form.displayName = 'Mirai:Core:Checkout:Form';
Form.propTypes = {
  children: _propTypes.default.node,
  dataSource: _propTypes.default.shape({
    form: _propTypes.default.shape({})
  }),
  showErrors: _propTypes.default.bool,
  variant: _propTypes.default.string,
  onError: _propTypes.default.func
};
//# sourceMappingURL=Checkout.Form.js.map