"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 _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,
      cart = [],
      extras: propExtras = [],
      taxesType,
      visible = false,
      onClose = () => {},
      onSubmit = () => {}
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    currencyFormat,
    translate
  } = (0, _locale.useLocale)();
  const {
    value: {
      currency,
      finder = {},
      hotel: {
        accommodationType: hotelAccommodationType,
        variants = {}
      } = {}
    } = {}
  } = (0, _dataSources.useStore)();
  const [extras, setExtras] = (0, _react.useState)(propExtras);
  (0, _react.useEffect)(() => {
    if (visible) {
      var _cart$;
      setExtras(propExtras);
      const roomType = cart === null || cart === void 0 ? 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 {
          price = 0
        } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
        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 {
      id,
      field,
      value
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    // ! 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, _value2;
    const next = extras.map(_ref2 => {
      let {
          selected = false
        } = _ref2,
        extra = _objectWithoutProperties(_ref2, _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(_ref3 => {
      let {
        selected
      } = _ref3;
      return selected;
    }).length;
    const {
      amount,
      nights,
      value,
      valueAmount,
      valueNights
    } = selectedExtra || {};
    const price = value === null || value === void 0 ? void 0 : (_value = value[valueAmount || amount]) === null || _value === void 0 ? void 0 : (_value2 = _value[valueNights || nights]) === null || _value2 === void 0 ? void 0 : _value2.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(_ref4 => {
      var _baseValue;
      let {
        amount,
        baseValue,
        nights,
        id,
        included,
        valueAmount,
        valueNights
      } = _ref4;
      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 {
      price
    } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    return value + price;
  }, 0);
  const totalExtras = extras.filter(item => item.selected).reduce(function (total) {
    var _value3;
    let {
      amount,
      nights,
      valueAmount,
      valueNights,
      value = {}
    } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
    return total + (((_value3 = value[valueAmount || amount][valueNights || nights]) === null || _value3 === void 0 ? void 0 : _value3.price) || 0);
  }, 0);
  const {
    place: {
      id: [id] = []
    } = {}
  } = finder;
  const {
    accommodationType = hotelAccommodationType
  } = variants[id] || {};
  const standaloneCard = extras.length === 1;
  const currencyFormatProps = {
    currency,
    maximumFractionDigits: 0,
    minimumFractionDigits: 0
  };
  const {
    testId
  } = others;
  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 {
      accommodationThreshold = 0,
      amount = 0,
      conditions,
      frequency,
      guestThreshold = 0,
      guestType,
      id,
      image,
      included = false,
      inputGuests = false,
      inputNights = false,
      nights = 0,
      selected = false,
      text,
      title,
      type,
      value = {},
      valueAmount = amount,
      valueNights = nights
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      price: total
    } = value[valueAmount][valueNights] || {};
    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(_ref5 => {
      let {
        selected
      } = _ref5;
      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