"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 _Rates = require("../../Rates/Rates.constants");
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 _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; }
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 _ref2 = _slicedToArray(_ref, 2),
      value = _ref2[1];
    return value.input !== _Checkout.INPUT.HTML;
  }).map(_ref3 => {
    let _ref4 = _slicedToArray(_ref3, 1),
      key = _ref4[0];
    return key;
  })
}))));
const Form = _ref5 => {
  var _dataSource$price, _dataSource$price$fin, _payment$config, _payment$info, _payment$info2;
  let children = _ref5.children,
    _ref5$dataSource = _ref5.dataSource,
    _ref5$dataSource2 = _ref5$dataSource === void 0 ? {} : _ref5$dataSource,
    currency = _ref5$dataSource2.currency,
    _ref5$dataSource2$rep = _ref5$dataSource2.repositories,
    _ref5$dataSource2$rep2 = _ref5$dataSource2$rep === void 0 ? {} : _ref5$dataSource2$rep,
    countries = _ref5$dataSource2$rep2.countries,
    _ref5$dataSource2$for = _ref5$dataSource2.form,
    schema = _ref5$dataSource2$for === void 0 ? {} : _ref5$dataSource2$for,
    _ref5$dataSource2$tra = _ref5$dataSource2.tracking,
    tracking = _ref5$dataSource2$tra === void 0 ? {} : _ref5$dataSource2$tra,
    dataSource = _objectWithoutProperties(_ref5$dataSource2, _excluded),
    _ref5$showErrors = _ref5.showErrors,
    showErrors = _ref5$showErrors === void 0 ? false : _ref5$showErrors,
    _ref5$onError = _ref5.onError,
    onError = _ref5$onError === void 0 ? () => {} : _ref5$onError,
    others = _objectWithoutProperties(_ref5, _excluded2);
  const _useDevice = (0, _ui.useDevice)(),
    isDesktop = _useDevice.isDesktop;
  const _useLocale = (0, _locale.useLocale)(),
    currencyFormat = _useLocale.currencyFormat,
    translate = _useLocale.translate;
  const _useStore = (0, _dataSources.useStore)(),
    set = _useStore.set,
    _useStore$value = _useStore.value,
    _useStore$value2 = _useStore$value === void 0 ? {} : _useStore$value,
    club = _useStore$value2.club,
    language = _useStore$value2.language,
    storePayment = _useStore$value2.payment,
    session = _useStore$value2.session;
  const clubDiscount = (dataSource === null || dataSource === void 0 || (_dataSource$price = dataSource.price) === null || _dataSource$price === void 0 || (_dataSource$price = _dataSource$price.discounts) === null || _dataSource$price === void 0 || (_dataSource$price$fin = _dataSource$price.find) === null || _dataSource$price$fin === void 0 || (_dataSource$price$fin = _dataSource$price$fin.call(_dataSource$price, discount => (discount === null || discount === void 0 ? void 0 : discount.type) === _Rates.DISCOUNT_TYPE.CLUB)) === null || _dataSource$price$fin === void 0 ? void 0 : _dataSource$price$fin.amount) || 0;
  const fieldContext = {
    clubDiscount,
    currency,
    currencyFormat
  };
  const formReady = (0, _react.useRef)(false);
  const _useState = (0, _react.useState)({}),
    _useState2 = _slicedToArray(_useState, 2),
    errorForm = _useState2[0],
    setErrorForm = _useState2[1];
  const _useState3 = (0, _react.useState)({}),
    _useState4 = _slicedToArray(_useState3, 2),
    errorPayment = _useState4[0],
    setErrorPayment = _useState4[1];
  const _useState5 = (0, _react.useState)(storage.get(key(dataSource, schema)) || Object.fromEntries(Object.entries(schema).map(_ref6 => {
      let _ref7 = _slicedToArray(_ref6, 2),
        key = _ref7[0],
        value = _ref7[1].value;
      return [key, value];
    }))),
    _useState6 = _slicedToArray(_useState5, 2),
    form = _useState6[0],
    setForm = _useState6[1];
  const _useState7 = (0, _react.useState)(),
    _useState8 = _slicedToArray(_useState7, 2),
    formTracked = _useState8[0],
    setFormTracked = _useState8[1];
  const _useState9 = (0, _react.useState)(false),
    _useState0 = _slicedToArray(_useState9, 2),
    modal = _useState0[0],
    setModal = _useState0[1];
  (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(_ref8 => {
      let _ref9 = _slicedToArray(_ref8, 2),
        field = _ref9[1];
      return field.required;
    }).map(_ref0 => {
      let _ref1 = _slicedToArray(_ref0, 1),
        key = _ref1[0];
      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 _await$ServiceCountry = await _services.ServiceCountry.info((0, _helpers.getCountryCode)(next.country, countries)),
        code = _await$ServiceCountry.code;
      if (code) next.phone = code;
    }
    const nextFields = getFields(next);
    const nextFiltered = nextFields.length < getFields(form).length ? Object.fromEntries(Object.entries(next).filter(_ref10 => {
      let _ref11 = _slicedToArray(_ref10, 1),
        key = _ref11[0];
      return Object.fromEntries(nextFields)[key] !== undefined;
    })) : undefined;
    setForm(nextFiltered || next);
  };
  const handleLeave = () => {
    const email = errorForm.email,
      firstName = errorForm.firstName,
      lastName = errorForm.lastName,
      phone = errorForm.phone;
    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(_ref12 => {
    let _ref13 = _slicedToArray(_ref12, 1),
      key = _ref13[0];
    return !!schema[key];
  }).filter(_ref14 => {
    let _ref15 = _slicedToArray(_ref14, 2),
      visible = _ref15[1].visible;
    return !visible || visible(value);
  });
  const _ref16 = dataSource || {},
    payment = _ref16.payment;
  const testId = others.testId;
  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(_ref17 => {
    let _ref18 = _slicedToArray(_ref17, 2),
      field = _ref18[1];
    return field.required;
  }).map(_ref19 => {
    let _ref20 = _slicedToArray(_ref19, 2),
      key = _ref20[0],
      _ref20$ = _ref20[1],
      field = _ref20$ === void 0 ? {} : _ref20$;
    return /*#__PURE__*/_react.default.createElement(_Checkout.FIELD[field.input] || _ui.InputText, (0, _helpers2.getFieldProps)(key, field, _objectSpread(_objectSpread({
      value: form[key],
      error: errorForm[key],
      language,
      session,
      translate
    }, dataSource), fieldContext), 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 || (_payment$config = _payment$config.publicKey) === null || _payment$config === void 0 ? void 0 : _payment$config[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(_ref21 => {
    let _ref22 = _slicedToArray(_ref21, 2),
      field = _ref22[1];
    return !field.required;
  }).map(_ref23 => {
    let _ref24 = _slicedToArray(_ref23, 2),
      key = _ref24[0],
      _ref24$ = _ref24[1],
      field = _ref24$ === void 0 ? {} : _ref24$;
    return /*#__PURE__*/_react.default.createElement(_Checkout.FIELD[field.input] || _ui.InputText, (0, _helpers2.getFieldProps)(key, field, _objectSpread(_objectSpread({
      value: form[key],
      error: errorForm[key],
      language,
      session,
      translate
    }, dataSource), fieldContext), 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,
  onError: _propTypes.default.func
};
//# sourceMappingURL=Checkout.Form.js.map