"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Occupation = void 0;
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 _Occupation = require("./Occupation.constants");
var _Occupation2 = require("./Occupation.Group");
var _Occupation3 = require("./Occupation.l10n");
var style = _interopRequireWildcard(require("./Occupation.module.css"));
var _prepareRoom = require("../../../helpers/prepareRoom");
var _helpers2 = require("../../helpers");
const _excluded = ["dataSource", "error", "maxRooms", "minRooms", "text", "type", "value", "warning", "onChange", "onError", "onSubmit", "onValid", "onWarning"];
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 _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 Occupation = exports.Occupation = /*#__PURE__*/_react.default.forwardRef((_ref, ref) => {
  let {
      dataSource = _Occupation.DATASOURCE,
      error,
      maxRooms,
      minRooms = 1,
      text,
      type = _helpers2.ACCOMMODATION_TYPE.ROOM,
      value = dataSource ? [...Array(minRooms)].map(() => (0, _prepareRoom.prepareRoom)(dataSource || _Occupation.DATASOURCE)) : [],
      warning,
      onChange = () => {},
      onError = () => {},
      onSubmit,
      onValid = () => {},
      onWarning = () => {}
    } = _ref,
    others = _objectWithoutProperties(_ref, _excluded);
  const {
    translate
  } = (0, _locale.useLocale)();
  const itemsRef = (0, _react.useRef)([]);
  const [scrollEnd, setScrollEnd] = (0, _react.useState)();
  const [withError, setWithError] = (0, _react.useState)(error);
  const [withWarning, setWithWarning] = (0, _react.useState)(false);
  const [currentDataSource, setCurrentDataSource] = (0, _react.useState)([]);
  (0, _react.useEffect)(() => {
    if (JSON.stringify(dataSource) !== JSON.stringify(currentDataSource)) setWithWarning(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentDataSource, dataSource]);
  (0, _react.useEffect)(() => {
    let nextValue = (0, _helpers.consolidateValue)(value, dataSource, currentDataSource);
    if (!nextValue) {
      setWithWarning(true);
      onWarning();
      nextValue = [(0, _prepareRoom.prepareRoom)(dataSource)];
    } else if (error && (0, _helpers.checkRoom)(nextValue, dataSource)) {
      handleValid();
    }
    if (JSON.stringify(dataSource) !== JSON.stringify(currentDataSource)) setCurrentDataSource(dataSource);
    // ! TODO: Check why doesnt work witn non-hotels
    if (JSON.stringify(nextValue) !== JSON.stringify(value)) handleChange(nextValue);

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataSource, value]);
  (0, _react.useEffect)(() => {
    var _itemsRef$current;
    setWithError(error);
    const roomIndex = value.findIndex(room => room.some(function () {
      let {
        ages = [],
        type
      } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return type === _Occupation.TYPE.CHILD && ages.some(age => age === undefined);
    }));
    if (roomIndex < 0) return;
    const scrollHeight = (0, _helpers.getScrollHeight)({
      hasAges: true,
      roomIndex,
      rooms: (_itemsRef$current = itemsRef.current) === null || _itemsRef$current === void 0 ? void 0 : _itemsRef$current.map(el => el === null || el === void 0 ? void 0 : el.scrollHeight)
    });
    if (scrollHeight >= 0) setScrollEnd(scrollEnd !== scrollHeight ? scrollHeight : scrollEnd + 0.1);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [error]);
  (0, _react.useEffect)(() => {
    if (warning === undefined) return;
    setWithWarning(warning);
  }, [warning]);
  const handleAddRoom = () => {
    var _itemsRef$current2;
    const {
      parentNode: {
        scrollHeight
      } = {}
    } = ((_itemsRef$current2 = itemsRef.current) === null || _itemsRef$current2 === void 0 ? void 0 : _itemsRef$current2.length) > 0 && itemsRef.current[0] || {};
    if (scrollHeight) setScrollEnd(scrollHeight);
    handleChange([...value, (0, _prepareRoom.prepareRoom)(dataSource)]);
    setWithWarning(false);
  };
  const handleRemoveRoom = (event, roomIndex, groupValue) => {
    event.stopPropagation();
    scroll(roomIndex, groupValue);
    handleChange(value.filter((_, index) => roomIndex !== index));
    itemsRef.current = [];
    setWithWarning(false);
  };
  const handleIndividual = (roomIndex, groupIndex, groupValue) => {
    dataSource[groupIndex].fulfill && scroll(roomIndex, groupValue);
    const nextValue = [...value];
    nextValue[roomIndex] = [...nextValue[roomIndex]] || [];
    nextValue[roomIndex][groupIndex] = groupValue.amount === 0 ? undefined : groupValue;
    handleChange(nextValue);
    setWithWarning(false);
  };
  const handleChange = nextValue => {
    onChange(nextValue);
    (0, _helpers.checkRoom)(nextValue, dataSource) ? handleValid() : onError(_Occupation.ERROR.NOT_FILLED);
  };
  const handleSubmit = () => {
    setWithWarning(false);
    onSubmit(value);
  };
  const handleValid = () => {
    setWithError(false);
    onValid();
  };
  const scroll = (roomIndex, groupValue) => {
    var _groupValue$ages, _itemsRef$current3;
    const scrollHeight = (0, _helpers.getScrollHeight)({
      hasAges: (groupValue === null || groupValue === void 0 ? void 0 : (_groupValue$ages = groupValue.ages) === null || _groupValue$ages === void 0 ? void 0 : _groupValue$ages.length) > 0,
      roomIndex,
      rooms: (_itemsRef$current3 = itemsRef.current) === null || _itemsRef$current3 === void 0 ? void 0 : _itemsRef$current3.map(el => el === null || el === void 0 ? void 0 : el.scrollHeight)
    });
    if (scrollHeight >= 0) setScrollEnd(scrollEnd !== scrollHeight ? scrollHeight : scrollEnd + 0.1);
  };
  const {
    testId
  } = others;
  const isValid = (0, _helpers.checkRoom)(value, dataSource);
  return /*#__PURE__*/_react.default.createElement(_ui.View, _extends({}, others, {
    role: "occupation",
    ref: ref,
    className: (0, _ui.styles)(style.container, others.className)
  }), (withError || withWarning) && /*#__PURE__*/_react.default.createElement(_ui.Notification, {
    error: withError,
    small: true,
    warning: withWarning,
    className: style.notification
  }, translate(withError ? _Occupation3.L10N.NOTIFICATION_ERROR_UNFILLED_FIELDS : _Occupation3.L10N.NOTIFICATION_WARNING_OCCUPATION)), /*#__PURE__*/_react.default.createElement(_ui.ScrollView, {
    scrollTo: scrollEnd,
    snap: false,
    className: style.scrollview
  }, value.map(function () {
    let room = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    let roomIndex = arguments.length > 1 ? arguments[1] : undefined;
    return /*#__PURE__*/_react.default.createElement(_ui.View, {
      key: "room:".concat(roomIndex),
      ref: el => itemsRef.current[roomIndex] = el,
      wide: true
    }, /*#__PURE__*/_react.default.createElement(_ui.View, {
      key: "room:header:".concat(roomIndex),
      row: true,
      className: style.header
    }, /*#__PURE__*/_react.default.createElement(_ui.Text, {
      action: true,
      bold: true
    }, translate({
      id: "".concat(_Occupation3.L10N.LABEL_PLACE_TYPE_COUNT.id, ".").concat(_Occupation.PLACE[type])
    }, {
      roomIndex: roomIndex + 1
    })), value.length > minRooms && /*#__PURE__*/_react.default.createElement(_ui.Button, {
      preventDefault: true,
      small: true,
      transparent: true,
      onPress: event => handleRemoveRoom(event, roomIndex, room[roomIndex]),
      testId: testId ? "".concat(testId, "-remove-room-").concat(roomIndex) : undefined
    }, translate(_Occupation3.L10N.ACTION_REMOVE))), dataSource.map((group, groupIndex) => /*#__PURE__*/_react.default.createElement(_Occupation2.OccupationGroup, _extends({}, group, {
      error: error,
      key: "room:".concat(roomIndex, ":").concat(groupIndex),
      value: room[groupIndex],
      onChange: value => handleIndividual(roomIndex, groupIndex, value),
      testId: "group-".concat(groupIndex)
    }))));
  })), /*#__PURE__*/_react.default.createElement(_ui.View, {
    row: true,
    className: (0, _ui.styles)(style.footer)
  }, /*#__PURE__*/_react.default.createElement(_ui.Button, {
    disabled: maxRooms && value.length >= maxRooms,
    preventDefault: true,
    secondary: true,
    className: style.buttonAdd,
    onPress: handleAddRoom,
    testId: testId ? "".concat(testId, "-add-room") : undefined
  }, translate({
    id: "".concat(_Occupation3.L10N.ACTION_ADD_PLACE_TYPE.id, ".").concat(_Occupation.PLACE[type])
  })), onSubmit && /*#__PURE__*/_react.default.createElement(_ui.Button, {
    disabled: !isValid,
    className: style.buttonSubmit,
    preventDefault: true,
    onPress: handleSubmit,
    testId: testId ? "".concat(testId, "-submit") : undefined
  }, text || translate(_Occupation3.L10N.ACTION_SEARCH))));
});
Occupation.displayName = 'Mirai:Core:Occupation';
Occupation.propTypes = {
  dataSource: _propTypes.default.arrayOf(_Occupation.SHAPE.DATASOURCE),
  error: _propTypes.default.bool,
  maxRooms: _propTypes.default.number,
  minRooms: _propTypes.default.number,
  text: _propTypes.default.string,
  type: _propTypes.default.oneOf(Object.values(_helpers2.ACCOMMODATION_TYPE)),
  value: _propTypes.default.arrayOf(_propTypes.default.arrayOf(_Occupation.SHAPE.VALUE)),
  warning: _propTypes.default.bool,
  onChange: _propTypes.default.func,
  onError: _propTypes.default.func,
  onSubmit: _propTypes.default.func,
  onValid: _propTypes.default.func,
  onWarning: _propTypes.default.func
};
//# sourceMappingURL=Occupation.js.map