"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 _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 _ref3;
  let {
      clubDiscount,
      items: propItems = [],
      priceFactor = 1,
      values,
      onOpen = () => {},
      onSubmit = () => {}
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    isMobile
  } = (0, _ui.useDevice)();
  const {
    translate
  } = (0, _locale.useLocale)();
  const {
    value: {
      currency,
      club = {},
      finder = {},
      hotel,
      id,
      locale,
      occupation: {
        maxRooms
      } = {},
      session,
      urlParams: {
        idoffers,
        roomTypeId
      } = {}
    } = {}
  } = (0, _dataSources.useStore)();
  const {
    place,
    promocode
  } = finder;
  const [allAmenities, setAllAmenities] = (0, _react.useState)(false);
  const [busy, setBusy] = (0, _react.useState)(false);
  const [counter, setCounter] = (0, _react.useState)(0);
  const [filters, setFilters] = (0, _react.useState)((0, _helpers.getAvailableFilters)(propItems, {
    priceFactor
  }));
  const [form, setForm] = (0, _react.useState)(_Filters4.DEFAULT_FORM);
  const [items, setItems] = (0, _react.useState)(propItems);
  const [visible, setVisible] = (0, _react.useState)(false);
  (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;
      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 {
      offer,
      promocode,
      roomType
    } = form || {};
    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 {
      items: nextItems
    } = (await (0, _helpers3.fetchRates)(params).catch(() => {})) || {};
    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 {
      availability = 0
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    return availability > 0;
  });
  const {
    length: boardsLength
  } = filters.boards;
  const inlineBoards = !isMobile || isMobile && boardsLength <= _Filters4.MAX_BOARDS - 1;
  const {
    name: roomTypeName
  } = (items === null || items === void 0 ? void 0 : items.find(function () {
    let {
      id
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    return id === parseInt(roomTypeId);
  })) || {};
  const {
    name: offerName
  } = ((_ref3 = has.offer && (items === null || items === void 0 ? void 0 : items.map(function () {
    let {
      boards = [],
      rates = []
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    const {
      rateId
    } = boards.find(function () {
      let {
        deals = []
      } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return deals.includes(idoffers.split(',')[0]);
    }) || {};
    return rates.find(_ref4 => {
      let {
        id
      } = _ref4;
      return id === rateId;
    });
  }))) === null || _ref3 === void 0 ? void 0 : _ref3[0]) || {};
  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 {
      field
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    return has[field];
  }).map(function () {
    let {
      field,
      title
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    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(_ref5 => {
    let {
      id,
      text,
      type
    } = _ref5;
    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(_ref6 => {
    let {
      id,
      text
    } = _ref6;
    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(_ref7 => {
    let {
      id,
      text
    } = _ref7;
    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