"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ModalExtras = 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 _helpers = require("./helpers");
var _ModalExtras = require("./ModalExtras.l10n");
var style = _interopRequireWildcard(require("./ModalExtras.module.css"));
var _helpers2 = require("../../../helpers");
var _helpers3 = require("../../helpers");
var _components = require("../Item/components");
const _excluded = ["busy", "cart", "extras", "taxesType", "visible", "onClose", "onSubmit"],
  _excluded2 = ["selected"];
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 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 _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 _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; }
const ModalExtras = _ref => {
  let busy = _ref.busy,
    _ref$cart = _ref.cart,
    cart = _ref$cart === void 0 ? [] : _ref$cart,
    _ref$extras = _ref.extras,
    propExtras = _ref$extras === void 0 ? [] : _ref$extras,
    taxesType = _ref.taxesType,
    _ref$visible = _ref.visible,
    visible = _ref$visible === void 0 ? false : _ref$visible,
    _ref$onClose = _ref.onClose,
    onClose = _ref$onClose === void 0 ? () => {} : _ref$onClose,
    _ref$onSubmit = _ref.onSubmit,
    onSubmit = _ref$onSubmit === void 0 ? () => {} : _ref$onSubmit,
    others = _objectWithoutProperties(_ref, _excluded);
  const _useLocale = (0, _locale.useLocale)(),
    currencyFormat = _useLocale.currencyFormat,
    translate = _useLocale.translate;
  const _useStore = (0, _dataSources.useStore)(),
    _useStore$value = _useStore.value,
    _useStore$value2 = _useStore$value === void 0 ? {} : _useStore$value,
    currency = _useStore$value2.currency,
    _useStore$value2$find = _useStore$value2.finder,
    finder = _useStore$value2$find === void 0 ? {} : _useStore$value2$find,
    _useStore$value2$hote = _useStore$value2.hotel,
    _useStore$value2$hote2 = _useStore$value2$hote === void 0 ? {} : _useStore$value2$hote,
    hotelAccommodationType = _useStore$value2$hote2.accommodationType,
    _useStore$value2$hote3 = _useStore$value2$hote2.variants,
    variants = _useStore$value2$hote3 === void 0 ? {} : _useStore$value2$hote3;
  const _useState = (0, _react.useState)(propExtras),
    _useState2 = _slicedToArray(_useState, 2),
    extras = _useState2[0],
    setExtras = _useState2[1];
  (0, _react.useEffect)(() => {
    if (visible) {
      var _cart$;
      setExtras(propExtras);
      const roomType = cart === null || cart === void 0 || (_cart$ = cart[0]) === null || _cart$ === void 0 ? void 0 : _cart$.roomName;
      const roomPrice = cart === null || cart === void 0 ? void 0 : cart.reduce(function (total) {
        let _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
          _ref2$price = _ref2.price,
          price = _ref2$price === void 0 ? 0 : _ref2$price;
        return total + price;
      }, 0);
      _dataSources.Event.publish(_helpers2.EVENT.METRICS, {
        id: _helpers2.METRICS_EVENTS.EXTRAS_READY,
        room_type: roomType,
        room_price: roomPrice,
        extras_count: propExtras === null || propExtras === void 0 ? void 0 : propExtras.length
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [propExtras, visible]);
  const handleChange = function () {
    let _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      id = _ref3.id,
      field = _ref3.field,
      value = _ref3.value;
    // ! Why parse Number()? should come from the service.
    setExtras(extras.map(extra => _objectSpread(_objectSpread({}, extra), {}, {
      [field]: extra.id === id ? parseInt(value) : extra[field]
    })));
  };
  const handleSelect = id => {
    var _value;
    const next = extras.map(_ref4 => {
      let _ref4$selected = _ref4.selected,
        selected = _ref4$selected === void 0 ? false : _ref4$selected,
        extra = _objectWithoutProperties(_ref4, _excluded2);
      return _objectSpread(_objectSpread({}, extra), {}, {
        selected: extra.id === id ? !selected : selected
      });
    });
    setExtras(next);
    const selectedExtra = next.find(extra => extra.id === id);
    const totalSelected = next.filter(_ref5 => {
      let selected = _ref5.selected;
      return selected;
    }).length;
    const _ref6 = selectedExtra || {},
      amount = _ref6.amount,
      nights = _ref6.nights,
      value = _ref6.value,
      valueAmount = _ref6.valueAmount,
      valueNights = _ref6.valueNights;
    const price = value === null || value === void 0 || (_value = value[valueAmount || amount]) === null || _value === void 0 || (_value = _value[valueNights || nights]) === null || _value === void 0 ? void 0 : _value.price;
    const position = next.findIndex(extra => extra.id === id) + 1;
    _dataSources.Event.publish(_helpers2.EVENT.METRICS, {
      id: _helpers2.METRICS_EVENTS.EXTRAS_INTERACTION,
      action: selectedExtra !== null && selectedExtra !== void 0 && selectedExtra.selected ? 'add' : 'remove',
      extra_name: selectedExtra === null || selectedExtra === void 0 ? void 0 : selectedExtra.title,
      extra_price: price,
      extra_position: position || undefined,
      total_extras_selected: totalSelected
    });
  };
  const handleSubmit = () => {
    onSubmit(extras.filter(item => item.selected || item.included).map(_ref7 => {
      var _baseValue;
      let amount = _ref7.amount,
        baseValue = _ref7.baseValue,
        nights = _ref7.nights,
        id = _ref7.id,
        included = _ref7.included,
        valueAmount = _ref7.valueAmount,
        valueNights = _ref7.valueNights;
      return {
        id,
        included,
        amount: parseInt(valueAmount || amount),
        nights: parseInt(valueNights || nights),
        value: (_baseValue = baseValue[valueAmount || amount][valueNights || nights]) === null || _baseValue === void 0 ? void 0 : _baseValue.price
      };
    }));
  };
  const hasSelected = extras.filter(item => !!item.selected).length > 0;
  const total = cart.reduce(function (value) {
    let _ref8 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      price = _ref8.price;
    return value + price;
  }, 0);
  const totalExtras = extras.filter(item => item.selected).reduce(function (total) {
    var _value2;
    let _ref9 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      amount = _ref9.amount,
      nights = _ref9.nights,
      valueAmount = _ref9.valueAmount,
      valueNights = _ref9.valueNights,
      _ref9$value = _ref9.value,
      value = _ref9$value === void 0 ? {} : _ref9$value;
    return total + (((_value2 = value[valueAmount || amount][valueNights || nights]) === null || _value2 === void 0 ? void 0 : _value2.price) || 0);
  }, 0);
  const _finder$place = finder.place,
    _finder$place2 = _finder$place === void 0 ? {} : _finder$place,
    _finder$place2$id = _finder$place2.id,
    _finder$place2$id2 = _finder$place2$id === void 0 ? [] : _finder$place2$id,
    _finder$place2$id3 = _slicedToArray(_finder$place2$id2, 1),
    id = _finder$place2$id3[0];
  const _ref0 = variants[id] || {},
    _ref0$accommodationTy = _ref0.accommodationType,
    accommodationType = _ref0$accommodationTy === void 0 ? hotelAccommodationType : _ref0$accommodationTy;
  const standaloneCard = extras.length === 1;
  const currencyFormatProps = {
    currency,
    maximumFractionDigits: 0,
    minimumFractionDigits: 0
  };
  const testId = others.testId;
  return /*#__PURE__*/_react.default.createElement(_ui.Modal, {
    fit: true,
    title: translate(_ModalExtras.L10N.LABEL_ANYTHING_ELSE_TO_ADD),
    visible: visible,
    onClose: onClose,
    className: style.modal,
    testId: testId
  }, /*#__PURE__*/_react.default.createElement(_ui.ScrollView, {
    scrollIndicator: true,
    scrollTo: visible ? 0.5 : undefined,
    snap: false,
    className: style.scrollView
  }, /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: style.container
  }, extras.map(function () {
    let _ref1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref1$accommodationTh = _ref1.accommodationThreshold,
      accommodationThreshold = _ref1$accommodationTh === void 0 ? 0 : _ref1$accommodationTh,
      _ref1$amount = _ref1.amount,
      amount = _ref1$amount === void 0 ? 0 : _ref1$amount,
      conditions = _ref1.conditions,
      frequency = _ref1.frequency,
      _ref1$guestThreshold = _ref1.guestThreshold,
      guestThreshold = _ref1$guestThreshold === void 0 ? 0 : _ref1$guestThreshold,
      guestType = _ref1.guestType,
      id = _ref1.id,
      image = _ref1.image,
      _ref1$included = _ref1.included,
      included = _ref1$included === void 0 ? false : _ref1$included,
      _ref1$inputGuests = _ref1.inputGuests,
      inputGuests = _ref1$inputGuests === void 0 ? false : _ref1$inputGuests,
      _ref1$inputNights = _ref1.inputNights,
      inputNights = _ref1$inputNights === void 0 ? false : _ref1$inputNights,
      _ref1$nights = _ref1.nights,
      nights = _ref1$nights === void 0 ? 0 : _ref1$nights,
      _ref1$selected = _ref1.selected,
      selected = _ref1$selected === void 0 ? false : _ref1$selected,
      text = _ref1.text,
      title = _ref1.title,
      type = _ref1.type,
      _ref1$value = _ref1.value,
      value = _ref1$value === void 0 ? {} : _ref1$value,
      _ref1$valueAmount = _ref1.valueAmount,
      valueAmount = _ref1$valueAmount === void 0 ? amount : _ref1$valueAmount,
      _ref1$valueNights = _ref1.valueNights,
      valueNights = _ref1$valueNights === void 0 ? nights : _ref1$valueNights;
    const _ref10 = value[valueAmount][valueNights] || {},
      total = _ref10.price;
    return /*#__PURE__*/_react.default.createElement(_ui.View, {
      key: id,
      wide: true,
      className: (0, _ui.styles)(style.card, standaloneCard && style.standalone, hasSelected && selected ? style.selected : undefined)
    }, /*#__PURE__*/_react.default.createElement(_ui.View, {
      className: style.image,
      style: {
        backgroundImage: "url(".concat(image, ")")
      }
    }), /*#__PURE__*/_react.default.createElement(_ui.View, {
      wide: true,
      className: [style.gap, style.offset, style.anchor]
    }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
      bold: true
    }, title), text && /*#__PURE__*/_react.default.createElement(_ui.Text, {
      small: true
    }, text), accommodationThreshold > 0 && /*#__PURE__*/_react.default.createElement(_ui.Notification, {
      inline: true,
      small: true,
      warning: true
    }, translate(_ModalExtras.L10N.LABEL_APPLIES_SELECTED_ROOMS, {
      value: accommodationThreshold
    })), guestThreshold > 0 && /*#__PURE__*/_react.default.createElement(_ui.Notification, {
      inline: true,
      small: true,
      warning: true
    }, translate(_ModalExtras.L10N.LABEL_APPLIES_INDIVIDUALS_RESERVATION, {
      value: guestThreshold
    })), conditions && /*#__PURE__*/_react.default.createElement(_ui.Text, {
      light: true,
      small: true
    }, conditions), (inputGuests || inputNights) && /*#__PURE__*/_react.default.createElement(_ui.View, {
      row: true,
      className: (0, _ui.styles)(style.gap, style.inputs)
    }, inputGuests && /*#__PURE__*/_react.default.createElement(_ui.InputSelect, {
      capitalize: true,
      name: "guests",
      label: (0, _helpers2.getGuestLabel)({
        plural: true,
        type: guestType
      }, translate),
      options: Array.from({
        length: amount
      }).map((_, index) => index + 1),
      value: valueAmount === null || valueAmount === void 0 ? void 0 : valueAmount.toString(),
      onChange: value => handleChange({
        id,
        field: 'valueAmount',
        value
      })
    }), inputNights && /*#__PURE__*/_react.default.createElement(_ui.InputSelect, {
      name: "nights",
      label: translate(_ModalExtras.L10N.LABEL_NIGHTS),
      options: Array.from({
        length: nights
      }).map((_, index) => index + 1),
      value: valueNights === null || valueNights === void 0 ? void 0 : valueNights.toString(),
      onChange: value => handleChange({
        id,
        field: 'valueNights',
        value
      })
    }))), /*#__PURE__*/_react.default.createElement(_ui.View, {
      row: true,
      className: [style.offset, style.spaceBetween]
    }, /*#__PURE__*/_react.default.createElement(_ui.View, null, /*#__PURE__*/_react.default.createElement(_ui.Text, {
      bold: true,
      headline: true
    }, total ? currencyFormat(_objectSpread(_objectSpread({}, currencyFormatProps), {}, {
      value: total
    })) : translate(_ModalExtras.L10N.LABEL_FREE)), /*#__PURE__*/_react.default.createElement(_ui.Text, {
      light: true,
      small: true
    }, (0, _helpers.getCaption)({
      accommodationType,
      amount,
      frequency,
      guestType,
      inputGuests,
      type,
      valueAmount,
      valueNights
    }, translate))), /*#__PURE__*/_react.default.createElement(_ui.Button, {
      small: true,
      secondary: !selected && !included,
      onPress: !included ? () => handleSelect(id) : undefined
    }, translate(included ? _ModalExtras.L10N.LABEL_INCLUDED : selected ? _ModalExtras.L10N.ACTION_REMOVE : _ModalExtras.L10N.ACTION_ADD))));
  }))), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: style.footer
  }, total > 0 && /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.total
  }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    bold: true,
    headline: true,
    level: 2
  }, currencyFormat(_objectSpread(_objectSpread({}, currencyFormatProps), {}, {
    value: total + totalExtras
  }))), !!taxesType && /*#__PURE__*/_react.default.createElement(_ui.Text, {
    light: true,
    small: true
  }, translate((0, _helpers3.getLabelTaxes)(taxesType))), /*#__PURE__*/_react.default.createElement(_components.PriceDetails, _extends({
    extras: extras.filter(_ref11 => {
      let selected = _ref11.selected;
      return selected;
    }),
    cart: cart,
    taxesType: taxesType
  }, others, {
    className: style.priceDetails
  }))), /*#__PURE__*/_react.default.createElement(_ui.Button, {
    busy: busy,
    onPress: handleSubmit,
    testId: testId ? "".concat(testId, "-submit") : undefined
  }, translate(hasSelected ? _ModalExtras.L10N.ACTION_CONTINUE : _ModalExtras.L10N.ACTION_CONTINUE_WITHOUT_EXTRAS))));
};
exports.ModalExtras = ModalExtras;
ModalExtras.propTypes = {
  busy: _propTypes.default.bool,
  cart: _propTypes.default.arrayOf(_propTypes.default.shape({})),
  extras: _propTypes.default.arrayOf(_propTypes.default.shape({})),
  taxesType: _propTypes.default.number,
  visible: _propTypes.default.bool,
  onClose: _propTypes.default.func,
  onSubmit: _propTypes.default.func
};
ModalExtras.displayName = 'Mirai:Core:Rates:ModalExtras';
//# sourceMappingURL=ModalExtras.js.map