"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Item = void 0;
var _locale = require("@mirai/locale");
var _ui = require("@mirai/ui");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _react = _interopRequireWildcard(require("react"));
var style = _interopRequireWildcard(require("./Item.module.css"));
var _Item = require("./Item.Preview");
var _Item2 = require("./Item.Rates");
var _Item3 = require("./Item.Summary");
var _shared__ = require("../../../__shared__");
var _helpers = require("../../helpers");
var _Rates = require("../../Rates.constants");
const _excluded = ["boards", "cancellations", "features", "filters", "metaBoard", "multiRoom", "priceFactor", "resultPosition", "rates", "selected", "onSelect"],
  _excluded2 = ["included"];
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 Item = exports.Item = /*#__PURE__*/_react.default.forwardRef((_ref, ref) => {
  let {
      boards = [],
      cancellations = [],
      features = {},
      filters = {},
      metaBoard,
      multiRoom,
      priceFactor = 1,
      resultPosition,
      rates: propRates = [],
      selected,
      onSelect = () => {}
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    translate
  } = (0, _locale.useLocale)();
  const [selectedBoard, setSelectedBoard] = (0, _react.useState)();
  (0, _react.useEffect)(() => {
    if (Object.keys(filters).length) updateSelectedBoard();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filters]);
  (0, _react.useEffect)(() => {
    if (!selectedBoard) updateSelectedBoard();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [boards]);
  (0, _react.useEffect)(() => {
    if (!metaBoard || metaBoard.roomId !== others.id || boards.length < 1) return;
    setSelectedBoard(boards.find(function () {
      let {
        id
      } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return id === metaBoard.id;
    }));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [metaBoard]);
  (0, _react.useEffect)(() => {
    if (!selected) return;
    const nextBoard = boards.find(board => board.id === selected.id);
    if (nextBoard) setSelectedBoard(nextBoard);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selected]);
  const updateSelectedBoard = () => {
    const [{
      id: cancellationId
    } = {}] = cancellations;
    const [{
      id: rateId
    } = {}] = rates;
    const nextBoard = boards.find(board => board.cancellationId === cancellationId && board.rateId === rateId);
    if (nextBoard) setSelectedBoard(nextBoard);
  };
  const handleBoard = board => {
    clearSelection();
    setSelectedBoard(board);
  };
  const handleCancellation = id => {
    clearSelection();
    setSelectedBoard(boards.find(_ref2 => {
      let {
        cancellationId
      } = _ref2;
      return cancellationId === id;
    }));
  };
  const handleRate = _ref3 => {
    let {
      id,
      cancellationId
    } = _ref3;
    clearSelection();
    setSelectedBoard(boards.find(board => board.cancellationId === cancellationId && board.rateId == id));
  };
  const findPrice = function (id) {
    let dataSource = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
    return (dataSource.find(function () {
      let item = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return item.id === id;
    }) || {}).price || 0;
  };
  const clearSelection = () => {
    multiRoom && (selected === null || selected === void 0 ? void 0 : selected.id) === id && onSelect(undefined);
  };
  const {
    columnMode,
    showAllBoards,
    showAllOffers,
    showOffersFirst
  } = features;
  const {
    id,
    cancellationId,
    rateId
  } = selectedBoard || {};
  const cancellationPrice = findPrice(cancellationId, cancellations);
  const rates = propRates.map(function () {
    let _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      {
        included = []
      } = _ref4,
      rate = _objectWithoutProperties(_ref4, _excluded2);
    const clubInclude = (0, _helpers.getClubInclude)((0, _helpers.getClubRate)({
      board: boards.filter(function () {
        let {
          rateId
        } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
        return rateId === rate.id;
      })[0],
      rate
    }));
    return _objectSpread(_objectSpread({}, rate), {}, {
      included: clubInclude && included.length ? [...included, translate(clubInclude)] : included
    });
  });
  const ratePrice = findPrice(rateId, rates);
  const visibleBoards = boards.filter(board => board.cancellationId === cancellationId && board.rateId === rateId);
  const isSoldOut = others.soldOut && (rates.length === 0 || Object.values(others.cart || {}).filter(function () {
    let {
      roomId
    } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    return roomId === (selectedBoard === null || selectedBoard === void 0 ? void 0 : selectedBoard.roomId);
  }).length > 0 && (selected === null || selected === void 0 ? void 0 : selected.id) != id);
  const props = _objectSpread(_objectSpread({}, others), {}, {
    availableBoards: boards,
    availableRates: rates,
    boards: showAllBoards ? boards.map(board => {
      const selectedBoard = board.cancellationId === cancellationId && board.rateId === rateId;
      let {
        increment
      } = board;
      if (!selectedBoard) {
        const boardCancellationPrice = findPrice(board.cancellationId, cancellations);
        const boardRatePrice = findPrice(board.rateId, rates);
        increment = increment - (cancellationPrice + ratePrice) + boardCancellationPrice + boardRatePrice;
      }
      return _objectSpread(_objectSpread({}, board), {}, {
        disabled: !selectedBoard,
        increment
      });
    }).filter(board => {
      if (!board.disabled) return true;
      const visible = !visibleBoards.find(item => item.name === board.name);
      if (visible) visibleBoards.push(board);
      return visible;
    }).sort((a, b) => a.increment - b.increment) : visibleBoards,
    cancellations,
    features,
    isSoldOut,
    multiRoom,
    priceFactor,
    promocodeForAll: boards.every(function () {
      let {
        confidential,
        deals = [],
        discount: {
          breakdown = []
        } = {}
      } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return breakdown.find(_ref5 => {
        let {
          type
        } = _ref5;
        return type === _Rates.DISCOUNT_TYPE.PROMOTION;
      }) || deals.length > 0 && confidential;
    }),
    rates: showOffersFirst ? rates.map(rate => _objectSpread(_objectSpread({}, rate), {}, {
      price: rate.price + findPrice(rate.cancellationId, cancellations)
    })).sort((a, b) => a.price - b.price) : showAllOffers ? rates.map(rate => {
      const selectedCancellation = rate.cancellationId === cancellationId;
      const price = selectedCancellation ? rate.price : rate.price - cancellationPrice + findPrice(rate.cancellationId, cancellations);
      return _objectSpread(_objectSpread({}, rate), {}, {
        disabled: !showOffersFirst && !selectedCancellation,
        price
      });
    }).sort((a, b) => a.price - b.price) : rates.filter(rate => rate.cancellationId === cancellationId),
    selected,
    selectedBoard,
    resultPosition,
    onSelect
  });
  return /*#__PURE__*/_react.default.createElement(_shared__.Card, {
    columnMode,
    disabled: isSoldOut,
    focus: selected && selected.id === id || metaBoard && boards.find(item => (metaBoard === null || metaBoard === void 0 ? void 0 : metaBoard.id) === item.id)
  }, /*#__PURE__*/_react.default.createElement(_ui.View, {
    ref: ref,
    className: [style.card, others.className]
  }, /*#__PURE__*/_react.default.createElement(_Item.Preview, props), !isSoldOut && /*#__PURE__*/_react.default.createElement(_Item2.Rates, _extends({}, props, {
    onBoard: handleBoard,
    onCancellation: handleCancellation,
    onRate: handleRate
  })), /*#__PURE__*/_react.default.createElement(_Item3.Summary, props)));
});
Item.displayName = 'Mirai:Core:Rates:Item';
Item.propTypes = {
  boards: _propTypes.default.arrayOf(_propTypes.default.shape({})),
  cancellations: _propTypes.default.arrayOf(_propTypes.default.shape({})),
  features: _propTypes.default.shape({}),
  filters: _propTypes.default.shape({}),
  metaBoard: _propTypes.default.shape({
    id: _propTypes.default.string,
    roomId: _propTypes.default.number
  }),
  multiRoom: _propTypes.default.bool,
  priceFactor: _propTypes.default.number,
  resultPosition: _propTypes.default.number,
  rates: _propTypes.default.arrayOf(_propTypes.default.shape({})),
  selected: _propTypes.default.shape({
    id: _propTypes.default.string
  }),
  showAllOffers: _propTypes.default.bool,
  onSelect: _propTypes.default.func
};
//# sourceMappingURL=Item.js.map