"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Filters = 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 _components = require("./components");
var _Filters = require("./Filters.Amenity");
var _Filters2 = require("./Filters.BookingOption");
var _Filters3 = require("./Filters.Button");
var _Filters4 = require("./Filters.constants");
var _Filters5 = require("./Filters.l10n");
var style = _interopRequireWildcard(require("./Filters.module.css"));
var _helpers = require("./helpers");
var _helpers2 = require("../../../helpers");
var _helpers3 = require("../../helpers");
var _components2 = require("../Item/components");
const _excluded = ["clubDiscount", "items", "priceFactor", "values", "onOpen", "onSubmit"];
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 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; }
let currentCurrency;
let currentPlace;
let memoizeForm;
const Filters = _ref => {
  var _ref9;
  let clubDiscount = _ref.clubDiscount,
    _ref$items = _ref.items,
    propItems = _ref$items === void 0 ? [] : _ref$items,
    _ref$priceFactor = _ref.priceFactor,
    priceFactor = _ref$priceFactor === void 0 ? 1 : _ref$priceFactor,
    values = _ref.values,
    _ref$onOpen = _ref.onOpen,
    onOpen = _ref$onOpen === void 0 ? () => {} : _ref$onOpen,
    _ref$onSubmit = _ref.onSubmit,
    onSubmit = _ref$onSubmit === void 0 ? () => {} : _ref$onSubmit,
    others = _objectWithoutProperties(_ref, _excluded);
  const _useDevice = (0, _ui.useDevice)(),
    isMobile = _useDevice.isMobile;
  const _useLocale = (0, _locale.useLocale)(),
    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$club = _useStore$value2.club,
    club = _useStore$value2$club === void 0 ? {} : _useStore$value2$club,
    _useStore$value2$find = _useStore$value2.finder,
    finder = _useStore$value2$find === void 0 ? {} : _useStore$value2$find,
    hotel = _useStore$value2.hotel,
    id = _useStore$value2.id,
    locale = _useStore$value2.locale,
    _useStore$value2$occu = _useStore$value2.occupation,
    _useStore$value2$occu2 = _useStore$value2$occu === void 0 ? {} : _useStore$value2$occu,
    maxRooms = _useStore$value2$occu2.maxRooms,
    session = _useStore$value2.session,
    _useStore$value2$urlP = _useStore$value2.urlParams,
    _useStore$value2$urlP2 = _useStore$value2$urlP === void 0 ? {} : _useStore$value2$urlP,
    idoffers = _useStore$value2$urlP2.idoffers,
    roomTypeId = _useStore$value2$urlP2.roomTypeId;
  const place = finder.place,
    promocode = finder.promocode;
  const _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    allAmenities = _useState2[0],
    setAllAmenities = _useState2[1];
  const _useState3 = (0, _react.useState)(false),
    _useState4 = _slicedToArray(_useState3, 2),
    busy = _useState4[0],
    setBusy = _useState4[1];
  const _useState5 = (0, _react.useState)(0),
    _useState6 = _slicedToArray(_useState5, 2),
    counter = _useState6[0],
    setCounter = _useState6[1];
  const _useState7 = (0, _react.useState)((0, _helpers.getAvailableFilters)(propItems, {
      priceFactor
    })),
    _useState8 = _slicedToArray(_useState7, 2),
    filters = _useState8[0],
    setFilters = _useState8[1];
  const _useState9 = (0, _react.useState)(_Filters4.DEFAULT_FORM),
    _useState0 = _slicedToArray(_useState9, 2),
    form = _useState0[0],
    setForm = _useState0[1];
  const _useState1 = (0, _react.useState)(propItems),
    _useState10 = _slicedToArray(_useState1, 2),
    items = _useState10[0],
    setItems = _useState10[1];
  const _useState11 = (0, _react.useState)(false),
    _useState12 = _slicedToArray(_useState11, 2),
    visible = _useState12[0],
    setVisible = _useState12[1];
  (0, _react.useEffect)(() => {
    const nextForm = memoizeForm || _objectSpread(_objectSpread({}, _Filters4.DEFAULT_FORM), {}, {
      offer: idoffers ? !!idoffers : undefined,
      promocode: promocode ? !!promocode : undefined,
      roomType: roomTypeId ? !!roomTypeId : undefined
    });
    setForm(nextForm);
    setCounter((0, _helpers.countFilters)(nextForm));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  (0, _react.useEffect)(() => {
    if (!form.priceRange || currentCurrency !== undefined && currentCurrency === currency) return;
    currentCurrency = currency;
    const nextForm = _objectSpread(_objectSpread({}, form), {}, {
      priceRange: undefined
    });
    setForm(nextForm);
    setCounter((0, _helpers.countFilters)(nextForm));
    onSubmit(_objectSpread(_objectSpread({}, nextForm), {}, {
      strictSearch: (0, _helpers.getStrictSearch)(nextForm)
    }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currency]);
  (0, _react.useEffect)(() => {
    if (!place || currentPlace !== undefined && JSON.stringify(currentPlace) === JSON.stringify(place)) return;
    if (currentPlace !== undefined) {
      setForm(_Filters4.DEFAULT_FORM);
      setCounter((0, _helpers.countFilters)(_Filters4.DEFAULT_FORM));
      onSubmit(_Filters4.DEFAULT_FORM);
    }
    currentPlace = place;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [place]);
  (0, _react.useEffect)(() => {
    const setNextState = nextForm => {
      setForm(nextForm);
      setCounter((0, _helpers.countFilters)(nextForm));
    };
    const setClubPromocode = _ref2 => {
      let promocode = _ref2.promocode;
      return setNextState(_objectSpread(_objectSpread({}, form), {}, {
        promocode
      }));
    };
    _dataSources.Event.subscribe(_helpers2.EVENT.RATES_FILTER_PROMOCODE, setClubPromocode);
    return () => _dataSources.Event.unsubscribe(_helpers2.EVENT.RATES_FILTER_PROMOCODE, setClubPromocode);
  }, [form]);
  (0, _react.useEffect)(() => {
    if (JSON.stringify(propItems) !== JSON.stringify(items)) setItems(propItems);
    const nextFilters = (0, _helpers.getAvailableFilters)(propItems, {
      priceFactor
    });
    if (JSON.stringify(nextFilters) !== JSON.stringify(filters)) setFilters(nextFilters);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [propItems]);
  (0, _react.useEffect)(() => {
    if (!values || Object.keys(values).length === 0) return;
    if (JSON.stringify(values) !== JSON.stringify(form)) {
      setForm(values);
      setCounter((0, _helpers.countFilters)(values));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [values]);
  const handleModal = () => {
    const next = !visible;
    setVisible(next);
    if (next) {
      onOpen();
    }
  };
  const handleAmenity = (id, value) => {
    setForm(_objectSpread(_objectSpread({}, form), {}, {
      amenities: value ? [...form.amenities, id] : form.amenities.filter(item => item !== id)
    }));
  };
  const handleOption = (field, id) => {
    setForm(_objectSpread(_objectSpread({}, form), {}, {
      [field]: form[field] === id ? undefined : id
    }));
  };
  const handleRange = (field, value) => {
    setForm(_objectSpread(_objectSpread({}, form), {}, {
      [field]: value
    }));
  };
  const handleBookingOption = async (field, value) => {
    const next = _objectSpread(_objectSpread({}, form), {}, {
      [field]: value
    });
    setForm(next);
    if (field !== 'freeCancellation') await fetch(next);
  };
  const handleClearAll = () => {
    const _ref3 = form || {},
      offer = _ref3.offer,
      promocode = _ref3.promocode,
      roomType = _ref3.roomType;
    setAllAmenities(false);
    setForm(_objectSpread({}, _Filters4.DEFAULT_FORM));
    (offer || promocode || roomType) && fetch(_Filters4.DEFAULT_FORM);
  };
  const handleSubmit = () => {
    var _form$amenities;
    memoizeForm = form;
    setVisible(false);
    const nextCounter = (0, _helpers.countFilters)(form);
    setCounter(nextCounter);
    _dataSources.Event.publish(_helpers2.EVENT.METRICS, {
      id: _helpers2.METRICS_EVENTS.RATES_INTERACTION,
      action: 'filter_applied',
      filter_used_cancellation: !!form.freeCancellation,
      filter_used_board: !!form.board,
      filter_used_price: !!form.priceRange,
      filter_used_amenities: ((_form$amenities = form.amenities) === null || _form$amenities === void 0 ? void 0 : _form$amenities.length) > 0,
      filter_used_bed: !!form.bedType,
      filter_used_size: !!form.sizeRange
    });
    onSubmit(_objectSpread(_objectSpread({}, form), {}, {
      strictSearch: (0, _helpers.getStrictSearch)(form)
    }));
  };
  const fetch = async next => {
    setBusy(true);
    const strictSearch = (0, _helpers.getStrictSearch)(next);
    const cart = []; // ! TODO: [MF-2006] Store should get the current cart of <Rates>
    const params = {
      cart,
      club,
      clubDiscount,
      finder,
      hotel,
      id,
      locale,
      maxRooms,
      session,
      strictSearch
    };
    const _ref4 = (await (0, _helpers3.fetchRates)(params).catch(() => {})) || {},
      nextItems = _ref4.items;
    setItems(nextItems);
    if (nextItems) setFilters((0, _helpers.getAvailableFilters)(nextItems, {
      priceFactor
    }));
    setBusy(false);
  };
  const has = {
    freeCancellation: true || !!filters.freeCancellation,
    // * We'll activate freeCancellation filter always.
    offer: !!idoffers,
    promocode: !!promocode,
    roomType: !!roomTypeId
  };
  const filteredItems = (0, _helpers3.select)(items, form, {
    priceFactor
  }).filter(function () {
    let _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref5$availability = _ref5.availability,
      availability = _ref5$availability === void 0 ? 0 : _ref5$availability;
    return availability > 0;
  });
  const boardsLength = filters.boards.length;
  const inlineBoards = !isMobile || isMobile && boardsLength <= _Filters4.MAX_BOARDS - 1;
  const _ref6 = (items === null || items === void 0 ? void 0 : items.find(function () {
      let _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        id = _ref7.id;
      return id === parseInt(roomTypeId);
    })) || {},
    roomTypeName = _ref6.name;
  const _ref8 = ((_ref9 = has.offer && (items === null || items === void 0 ? void 0 : items.map(function () {
      let _ref0 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref0$boards = _ref0.boards,
        boards = _ref0$boards === void 0 ? [] : _ref0$boards,
        _ref0$rates = _ref0.rates,
        rates = _ref0$rates === void 0 ? [] : _ref0$rates;
      const _ref1 = boards.find(function () {
          let _ref10 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
            _ref10$deals = _ref10.deals,
            deals = _ref10$deals === void 0 ? [] : _ref10$deals;
          return deals.includes(idoffers.split(',')[0]);
        }) || {},
        rateId = _ref1.rateId;
      return rates.find(_ref11 => {
        let id = _ref11.id;
        return id === rateId;
      });
    }))) === null || _ref9 === void 0 ? void 0 : _ref9[0]) || {},
    offerName = _ref8.name;
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_Filters3.Button, {
    counter,
    onPress: handleModal
  }), /*#__PURE__*/_react.default.createElement(_ui.Modal, {
    fit: true,
    portal: true,
    title: translate(_Filters5.L10N.LABEL_FILTERS),
    visible: visible,
    onClose: handleModal,
    className: [style.modal, others.className]
  }, /*#__PURE__*/_react.default.createElement(_ui.ScrollView, {
    scrollIndicator: true,
    scrollTo: visible ? 0.5 : undefined,
    snap: false,
    className: style.scrollView
  }, /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.section
  }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    bold: true,
    headline: true
  }, translate(_Filters5.L10N.LABEL_BOOKING_OPTIONS)), (0, _helpers.getBookingOptions)(!!idoffers && idoffers.split(',').length === 1).filter(function () {
    let _ref12 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      field = _ref12.field;
    return has[field];
  }).map(function () {
    let _ref13 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      field = _ref13.field,
      title = _ref13.title;
    return /*#__PURE__*/_react.default.createElement(_Filters2.BookingOption, {
      key: field,
      checked: form[field],
      field,
      title,
      offerName,
      roomName: roomTypeName,
      promocode: promocode === null || promocode === void 0 ? void 0 : promocode.toUpperCase(),
      onChange: handleBookingOption
    });
  })), boardsLength > 1 && /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.section
  }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    bold: true,
    headline: true
  }, translate(_Filters5.L10N.LABEL_ACCOMMODATION_PLAN)), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: inlineBoards,
    className: (0, _ui.styles)(style.boards, inlineBoards && style.inline)
  }, filters.boards.map(_ref14 => {
    let id = _ref14.id,
      text = _ref14.text,
      type = _ref14.type;
    return /*#__PURE__*/_react.default.createElement(_components2.Option, {
      checked: form.board === type,
      key: "board:".concat(id),
      inline: inlineBoards,
      outlined: true,
      title: text,
      onPress: () => handleOption('board', type),
      className: style.option
    });
  }))), filters.prices.length > 1 && /*#__PURE__*/_react.default.createElement(_components.InputRange, {
    caption: translate(priceFactor === 1 ? _Filters5.L10N.LABEL_SET_PRICE_RANGE : _Filters5.L10N.LABEL_NIGHTLY_PRICES),
    dataSource: filters.prices,
    resolution: isMobile || filters.prices.length <= 8 ? 6 : 10,
    title: translate(_Filters5.L10N.LABEL_PRICE_RANGE),
    unit: (0, _locale.currencySymbol)(currency, {
      locale
    }),
    value: form.priceRange,
    onChange: value => handleRange('priceRange', value),
    className: style.section
  }), /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.section
  }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    bold: true,
    headline: true,
    wide: true
  }, translate(_Filters5.L10N.LABEL_AMENITIES)), /*#__PURE__*/_react.default.createElement(_ui.View, null, /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: style.amenities
  }, filters.amenities.filter(item => item.highlight).map(_ref15 => {
    let id = _ref15.id,
      text = _ref15.text;
    return /*#__PURE__*/_react.default.createElement(_Filters.Amenity, {
      checked: form.amenities.includes(id),
      id: id,
      key: id,
      label: text,
      onChange: handleAmenity
    });
  })), allAmenities ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    action: true,
    bold: true,
    wide: true,
    className: style.textOthers
  }, translate(_Filters5.L10N.LABEL_OTHERS)), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: style.amenities
  }, filters.amenities.filter(item => !item.highlight).map(_ref16 => {
    let id = _ref16.id,
      text = _ref16.text;
    return /*#__PURE__*/_react.default.createElement(_Filters.Amenity, {
      checked: form.amenities.includes(id),
      id: id,
      key: id,
      label: text,
      onChange: handleAmenity
    });
  }))) : /*#__PURE__*/_react.default.createElement(_ui.Action, {
    onPress: () => setAllAmenities(true)
  }, translate(_Filters5.L10N.ACTION_VIEW_MORE)))), filters.bedTypes.length > 1 && /*#__PURE__*/_react.default.createElement(_ui.View, {
    className: style.section
  }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
    bold: true,
    headline: true,
    wide: true
  }, translate(_Filters5.L10N.LABEL_BED_TYPE)), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true
  }, filters.bedTypes.map(bedType => /*#__PURE__*/_react.default.createElement(_components2.Option, {
    key: "bedType:".concat(bedType),
    checked: form.bedType === bedType,
    icon: bedType === 1 ? _helpers2.ICON.BED_SINGLE : _helpers2.ICON.BED_DOUBLE,
    inline: true,
    outlined: true,
    title: translate(bedType === 1 ? _Filters5.L10N.LABEL_BED_TYPE_SINGLE : _Filters5.L10N.LABEL_BED_TYPE_DOUBLE),
    onPress: () => handleOption('bedType', bedType),
    className: style.option
  })))), filters.sizes.length > 1 && /*#__PURE__*/_react.default.createElement(_components.InputRange, {
    dataSource: filters.sizes,
    resolution: isMobile ? 4 : 6,
    title: translate(_Filters5.L10N.LABEL_ROOM_SIZE),
    unit: filters.sizeUnit,
    value: form.sizeRange,
    onChange: value => handleRange('sizeRange', value),
    className: style.section
  })), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: [style.footer, style.spaceBetween]
  }, /*#__PURE__*/_react.default.createElement(_ui.Button, {
    transparent: true,
    onPress: handleClearAll
  }, translate(_Filters5.L10N.ACTION_CLEAR_ALL)), /*#__PURE__*/_react.default.createElement(_ui.Button, {
    busy: busy,
    disabled: !filteredItems.length,
    onPress: handleSubmit
  }, translate(filteredItems.length ? _Filters5.L10N.LABEL_SHOW_COUNT_RESULTS : _Filters5.L10N.LABEL_NO_EXACT_MATCHES, {
    count: filteredItems.length
  })))));
};
exports.Filters = Filters;
Filters.displayName = 'Mirai:Core:Rates:Filters';
Filters.propTypes = {
  clubDiscount: _propTypes.default.bool,
  items: _propTypes.default.arrayOf(_propTypes.default.shape({})),
  priceFactor: _propTypes.default.number,
  values: _propTypes.default.shape({}),
  onOpen: _propTypes.default.func,
  onSubmit: _propTypes.default.func
};
//# sourceMappingURL=Filters.js.map