"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Checkout = void 0;
var _dataSources = require("@mirai/data-sources");
var _locale = require("@mirai/locale");
var _services = require("@mirai/services");
var _ui = require("@mirai/ui");
var _react = _interopRequireWildcard(require("react"));
var _Checkout = require("./Checkout.constants");
var _Checkout2 = require("./Checkout.l10n");
var style = _interopRequireWildcard(require("./Checkout.module.css"));
var _Checkout3 = _interopRequireDefault(require("./Checkout.skeleton"));
var _partials = require("./partials");
var _Core = require("../../Core.constants");
var _getSearchProps = require("../../helpers/getSearchProps");
var _shared__ = require("../__shared__");
var _Booking = require("../Booking/partials/Booking.ModalAgency");
var _Header = require("../Header");
var _helpers = require("../helpers");
var _Rates = require("../Rates/Rates.constants");
const _excluded = ["posError"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
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 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); }
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 _objectDestructuringEmpty(t) { if (null == t) throw new TypeError("Cannot destructure " + t); }
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); }
const Checkout = _ref => {
  let others = _extends({}, (_objectDestructuringEmpty(_ref), _ref));
  const {
    isDesktop
  } = (0, _ui.useDevice)();
  const {
    translate
  } = (0, _locale.useLocale)();
  const _useStore = (0, _dataSources.useStore)(),
    {
      value: {
        checkout = {},
        currency,
        finder = {},
        hotel,
        language,
        locale,
        payment: storePayment = {},
        session,
        skeleton = false,
        urlParams: {
          posError: tpvError
        } = {},
        variant
      }
    } = _useStore,
    urlParams = _objectWithoutProperties(_useStore.value.urlParams, _excluded);
  const [busy, setBusy] = (0, _react.useState)(false);
  const [dataSource, setDataSource] = (0, _react.useState)();
  const [error, setError] = (0, _react.useState)();
  const [requiredFields, setRequiredFields] = (0, _react.useState)();
  const [modalAgency, setModalAgency] = (0, _react.useState)(false);
  const [responseError, setResponseError] = (0, _react.useState)();
  const [validateError, setValidateError] = (0, _react.useState)();
  const checkoutMetricsSent = (0, _react.useRef)(false);
  (0, _react.useEffect)(() => {
    var _price$discounts, _price$discounts$find, _price$discounts$find2, _dataSource$payment, _dataSource$payment$c;
    if (skeleton || !dataSource || checkoutMetricsSent.current) return;
    const {
      countryCode,
      price = {},
      payment = {}
    } = dataSource;
    const mandatoryFieldsCount = Object.values(dataSource.form || {}).filter(function () {
      let field = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return field.required && field.input !== _Checkout.INPUT.OPTION && (!field.countries || field.countries.includes(countryCode));
    }).length;
    const methods = Array.isArray(payment.methods) ? payment.methods : Object.keys(payment.methods || {});
    const paymentMethodsAvailable = (methods || []).map(method => method);
    const paymentMethodsCount = paymentMethodsAvailable.length;
    const extrasSelectedCount = (dataSource.extras || []).length + (dataSource.details || []).reduce(function (total) {
      let {
        extras = []
      } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      return total + extras.length;
    }, 0);
    _dataSources.Event.publish(_helpers.EVENT.METRICS, _objectSpread(_objectSpread({
      id: _helpers.METRICS_EVENTS.CHECKOUT_READY
    }, (0, _getSearchProps.getSearchProps)({
      store: {
        finder,
        currency,
        language,
        locale,
        urlParams
      },
      dataSource
    })), {}, {
      is_loyalty_rate: urlParams.applyClubDiscount === 'true',
      loyalty_savings_amount: ((_price$discounts = price.discounts) === null || _price$discounts === void 0 ? void 0 : (_price$discounts$find = _price$discounts.find) === null || _price$discounts$find === void 0 ? void 0 : (_price$discounts$find2 = _price$discounts$find.call(_price$discounts, discount => discount.type === _Rates.DISCOUNT_TYPE.CLUB)) === null || _price$discounts$find2 === void 0 ? void 0 : _price$discounts$find2.amount) || 0,
      total_amount: price.total,
      extras_selected_count: extrasSelectedCount,
      payment_gateway: ((_dataSource$payment = dataSource.payment) === null || _dataSource$payment === void 0 ? void 0 : (_dataSource$payment$c = _dataSource$payment.config) === null || _dataSource$payment$c === void 0 ? void 0 : _dataSource$payment$c.provider) || undefined,
      payment_methods_available: paymentMethodsAvailable,
      payment_methods_count: paymentMethodsCount,
      mandatory_fields_count: mandatoryFieldsCount,
      is_refundable: urlParams.refundable === 'true'
    }));
    checkoutMetricsSent.current = true;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataSource]);
  (0, _react.useEffect)(() => {
    if (skeleton) return;
    (async () => await fetch())();

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [locale, session]);
  (0, _react.useEffect)(() => {
    if (!validateError) return;
    const {
      EXTRA_CHANGED,
      NOT_ENOUGH_ROOMS,
      NOT_ENOUGH_ROOMS_FOR_OFFER,
      NO_SELECTED_ROOMS,
      PRICE_CHANGED
    } = _Core.VALIDATE_ERROR;
    (async () => {
      const {
        price,
        type
      } = validateError;
      if (type === PRICE_CHANGED && price) {
        (0, _helpers.replaceUrlParams)({
          totalPrice: price
        });
        await fetch(price);
      } else if ([EXTRA_CHANGED, NOT_ENOUGH_ROOMS, NOT_ENOUGH_ROOMS_FOR_OFFER, NO_SELECTED_ROOMS].includes(type)) {
        document.location.href = (0, _helpers.getRatesUrl)(_objectSpread({
          currency,
          language,
          notification: type,
          promocode: finder.promocode || '',
          variant
        }, urlParams));
      } else {
        setResponseError(_Core.ERROR.UNKNOWN);
      }
    })();

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [validateError]);
  const fetch = async price => {
    setBusy(true);
    let cancel = false;
    const response = await _services.ServiceBooking.checkout(_objectSpread(_objectSpread({
      currency,
      hotel,
      language,
      locale,
      session
    }, urlParams), price ? {
      totalPrice: price
    } : undefined)).catch(error => {
      if (error.type) {
        setValidateError(validateError !== null && validateError !== void 0 && validateError.price && error !== null && error !== void 0 && error.price ? {
          type: _Core.VALIDATE_ERROR.URL_GENERIC
        } : error);
        cancel = true;
      } else setResponseError(error);
    });
    if (cancel) return;
    setBusy(false);
    setValidateError();
    if (response) {
      setDataSource(response);
      const betterPrice = price && price < urlParams.totalPrice;
      _dataSources.Event.publish(_helpers.EVENT.CHECKOUT_RESPONSE, {
        event: _helpers.EVENT.CHECKOUT_RESPONSE,
        response
      });
      if (betterPrice !== undefined) {
        _dataSources.Event.publish(_helpers.EVENT.NOTIFICATION, _objectSpread(_objectSpread({}, betterPrice ? {
          success: true
        } : {
          warning: true
        }), {}, {
          defaultMessage: translate(betterPrice ? _Checkout2.L10N.NOTIFICATION_BETTER_PRICE : _Checkout2.L10N.NOTIFICATION_PRICE_CHANGED)
        }));
        _dataSources.Event.publish(_helpers.EVENT.METRICS, {
          id: _helpers.METRICS_EVENTS.CHECKOUT_INTERACTION,
          action: 'notification_show',
          notification_type: betterPrice ? 'success' : 'warning',
          notification_message: betterPrice ? 'price_decreased' : 'price_increased'
        });
      }
    }
  };
  const handleModalAgency = () => {
    setModalAgency(true);
  };
  const handleErrorConfirmation = () => {
    Object.entries(error || {}).forEach(_ref2 => {
      let [field, value] = _ref2;
      if (!value) return;
      _dataSources.Event.publish(_helpers.EVENT.METRICS, {
        id: _helpers.METRICS_EVENTS.CHECKOUT_INTERACTION,
        action: 'field_error',
        field_name: field,
        field_group: Object.keys(checkout).find(key => key === field) ? 'personal_data' : 'payment_data',
        error_type: value !== null && value !== void 0 && value.required || !storePayment[field] ? 'required_empty' : 'invalid_format'
      });
    });
    window.scrollTo({
      top: 0,
      behavior: 'smooth'
    });
    setRequiredFields(error);
  };
  const {
    agency = {},
    payment
  } = dataSource || {};
  const response = dataSource !== undefined;
  const hasRequiredFields = Object.keys(requiredFields || {}).length > 0;
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_Header.Header, null), /*#__PURE__*/_react.default.createElement(_ui.View, {
    role: "checkout",
    tag: "checkout",
    testId: others.testId,
    className: (0, _ui.styles)(style.container, others.className)
  }, /*#__PURE__*/_react.default.createElement(_ui.Progress, {
    indeterminate: true,
    visible: busy || !response && !responseError,
    className: style.progress
  }), response ? /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: isDesktop,
    className: style.content
  }, /*#__PURE__*/_react.default.createElement(_ui.View, {
    wide: true,
    className: style.main
  }, hasRequiredFields && /*#__PURE__*/_react.default.createElement(_shared__.NotificationRequiredFields, {
    form: "checkout",
    schema: dataSource === null || dataSource === void 0 ? void 0 : dataSource.form,
    values: requiredFields
  }), (agency.name || !payment || tpvError) && /*#__PURE__*/_react.default.createElement(_ui.Notification, {
    error: tpvError,
    small: true,
    info: true,
    wide: true,
    className: (0, _ui.styles)(style.agency, others.className)
  }, !tpvError && !payment && "".concat(translate(_Checkout2.L10N.NOTIFICATION_NO_CARD), " "), !tpvError && agency.name && translate(_Checkout2.L10N.NOTIFICATION_AGENCY, {
    agency: agency.name,
    link: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ui.Action, {
      underline: true,
      small: true,
      onPress: handleModalAgency,
      className: (0, _ui.styles)(style.action)
    }, translate(_Checkout2.L10N.ACTION_MORE_INFO)))
  }), tpvError && translate(_Checkout2.L10N.NOTIFICATION_UNKNOWN_POS_ERROR)), !isDesktop && /*#__PURE__*/_react.default.createElement(_shared__.BookingSummary, {
    box: true,
    dataSource: dataSource
  }, /*#__PURE__*/_react.default.createElement(_shared__.BookingDetails, {
    dataSource: dataSource,
    expanded: true
  })), /*#__PURE__*/_react.default.createElement(_partials.Form, {
    dataSource: dataSource,
    showErrors: hasRequiredFields,
    onError: setError
  }), isDesktop && /*#__PURE__*/_react.default.createElement(_shared__.BookingDetails, {
    dataSource: dataSource,
    className: style.box
  }), /*#__PURE__*/_react.default.createElement(_shared__.BookingTerms, {
    dataSource: dataSource,
    small: true
  })), /*#__PURE__*/_react.default.createElement(_partials.Confirmation, {
    busy: busy,
    dataSource: dataSource,
    error: Object.keys(error || {}).length > 0,
    onError: handleErrorConfirmation,
    onValid: () => setRequiredFields()
  })) : responseError ? /*#__PURE__*/_react.default.createElement(_ui.Notification, {
    error: true,
    large: true
  }, translate(_Checkout2.L10N.NOTIFICATION_ERROR[(responseError === null || responseError === void 0 ? void 0 : responseError.code) || _Core.ERROR.UNKNOWN])) : /*#__PURE__*/_react.default.createElement(_Checkout3.default, null)), agency.name && /*#__PURE__*/_react.default.createElement(_Booking.ModalAgency, _extends({}, agency, {
    visible: modalAgency,
    onClose: () => setModalAgency(false)
  })), /*#__PURE__*/_react.default.createElement(_shared__.Footer, null));
};
exports.Checkout = Checkout;
Checkout.displayName = 'Mirai:Core:Checkout';
Checkout.propTypes = {};
//# sourceMappingURL=Checkout.js.map