import _extends from '@babel/runtime/helpers/extends';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import isEqual from '../../node_modules/lodash-es/isEqual.js';
import _omit from '../../node_modules/lodash-es/omit.js';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.array.slice.js';
import 'core-js/modules/es.object.get-own-property-descriptor.js';
import 'core-js/modules/es.object.get-own-property-descriptors.js';
import 'core-js/modules/es.object.keys.js';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.regexp.exec.js';
import 'core-js/modules/es.string.search.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import React__default, { useReducer, useMemo, useEffect } from 'react';
import PropTypes from 'prop-types';
import { usePrevious } from '../../hooks/usePrevious.js';
import { determineInitialState, tileCatalogReducer, TILE_ACTIONS } from './tileCatalogReducer.js';
import TileCatalog, { propTypes } from './TileCatalog.js';

var _excluded = ["isSelectedByDefault", "onSelection", "pagination", "search", "selectedTileId", "tiles"];
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; }

/**
 * Paging and searching happens on local state within the component
 */

var StatefulTileCatalog = function StatefulTileCatalog(_ref) {
  var isSelectedByDefault = _ref.isSelectedByDefault,
    onSelection = _ref.onSelection,
    pagination = _ref.pagination,
    search = _ref.search,
    selectedTileIdProp = _ref.selectedTileId,
    tilesProp = _ref.tiles,
    props = _objectWithoutProperties(_ref, _excluded);
  var initialState = determineInitialState(_objectSpread(_objectSpread({}, props), {}, {
    selectedTileId: selectedTileIdProp,
    isSelectedByDefault: isSelectedByDefault,
    tiles: tilesProp,
    search: search,
    pagination: pagination
  }));
  var onPage = pagination && pagination.onPage;
  var onSearch = search && search.onSearch;
  var _useReducer = useReducer(tileCatalogReducer, initialState),
    _useReducer2 = _slicedToArray(_useReducer, 2),
    state = _useReducer2[0],
    dispatch = _useReducer2[1];
  var tilesWithoutRenderContent = useMemo(function () {
    return tilesProp.map(function (tile) {
      return _omit(tile, 'renderContent');
    });
  }, [tilesProp]);
  var previousTiles = usePrevious(tilesWithoutRenderContent);
  useEffect(function () {
    if (!isEqual(tilesWithoutRenderContent, previousTiles)) {
      // If we get passed a new set of tiles reset!
      dispatch({
        type: TILE_ACTIONS.RESET,
        payload: _objectSpread(_objectSpread({}, props), {}, {
          selectedTileId: selectedTileIdProp,
          isSelectedByDefault: isSelectedByDefault,
          tiles: tilesProp,
          search: search,
          pagination: pagination
        })
      });
      // If we totally change the tiles data, we should generate a selection event for the initial default selection
      if (isSelectedByDefault && onSelection && tilesProp.length > 0 && !selectedTileIdProp) {
        onSelection(tilesProp[0].id);
      }
    }
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [tilesWithoutRenderContent, previousTiles]);
  useEffect(function () {
    if (selectedTileIdProp) {
      dispatch({
        type: TILE_ACTIONS.SELECT,
        payload: selectedTileIdProp
      });
    }
  }, [selectedTileIdProp]);
  var page = state.page,
    startingIndex = state.startingIndex,
    endingIndex = state.endingIndex,
    searchState = state.searchState,
    tiles = state.tiles,
    filteredTiles = state.filteredTiles,
    selectedTileId = state.selectedTileId;
  var handlePage = function handlePage() {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    dispatch({
      type: TILE_ACTIONS.PAGE_CHANGE,
      payload: args && args[0]
    });
    if (onPage) {
      onPage.apply(void 0, args);
    }
  };
  var handleSelection = function handleSelection(newSelectedTile) {
    dispatch({
      type: TILE_ACTIONS.SELECT,
      payload: newSelectedTile
    });
    if (onSelection) {
      onSelection(newSelectedTile);
    }
  };
  var handleSearch = function handleSearch(event) {
    var newSearch = event.target.value || '';
    dispatch({
      type: TILE_ACTIONS.SEARCH,
      payload: newSearch
    });
    if (onSearch) {
      for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }
      onSearch.apply(void 0, [newSearch].concat(args));
    }
  };
  var isFiltered = searchState !== '';
  return /*#__PURE__*/React__default.createElement(TileCatalog, _extends({}, props, {
    selectedTileId: selectedTileId
    // slice doesn't include the last index!
    ,
    tiles: isFiltered // if the tiles aren't filtered just show the raw prop so that there's no repaint
    ? filteredTiles.slice(startingIndex, endingIndex + 1) : tilesProp.slice(startingIndex, endingIndex + 1),
    search: _objectSpread(_objectSpread({}, search), {}, {
      onSearch: handleSearch,
      value: searchState
    }),
    pagination: _objectSpread(_objectSpread({}, pagination), {}, {
      page: page,
      onPage: handlePage,
      totalItems: isFiltered ? filteredTiles.length : tiles ? tiles.length : 0
    }),
    onSelection: handleSelection
  }));
};
StatefulTileCatalog.defaultProps = {
  isSelectedByDefault: true
};
StatefulTileCatalog.propTypes = _objectSpread(_objectSpread({}, propTypes), {}, {
  /** Will always select the first entry if set true */
  isSelectedByDefault: PropTypes.bool
});
StatefulTileCatalog.__docgenInfo = {
  "description": "Paging and searching happens on local state within the component",
  "methods": [],
  "displayName": "StatefulTileCatalog",
  "props": {
    "isSelectedByDefault": {
      "defaultValue": {
        "value": "true",
        "computed": false
      },
      "description": "Will always select the first entry if set true",
      "type": {
        "name": "bool"
      },
      "required": false
    }
  },
  "composes": ["./TileCatalog"]
};
var StatefulTileCatalog$1 = StatefulTileCatalog;

export { StatefulTileCatalog$1 as default };
