import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
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.find.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, { useMemo, useState, useCallback, useEffect } from 'react';
import PropTypes from 'prop-types';
import { EditingStyle, handleEditModeSelect, moveItemsInList } from '../../../utils/DragAndDropUtils.js';
import List from '../List.js';

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; }
var itemPropTypes = {
  id: PropTypes.string,
  content: PropTypes.shape({
    value: PropTypes.string,
    icon: PropTypes.node
  }),
  children: PropTypes.arrayOf(PropTypes.any),
  // TODO: make this recursive
  isSelectable: PropTypes.bool
};
var propTypes = {
  /** list title */
  title: PropTypes.string.isRequired,
  /** use search with default behavior */
  hasSearch: PropTypes.bool,
  /** action buttons on right side of list title */
  buttons: PropTypes.arrayOf(PropTypes.node),
  /** list editing style */
  editingStyle: PropTypes.oneOf([EditingStyle.Single, EditingStyle.Multiple, EditingStyle.SingleNesting, EditingStyle.MultipleNesting]),
  /** data source of list items */
  items: PropTypes.arrayOf(PropTypes.shape(itemPropTypes)).isRequired,
  /** use full height in list */
  isFullHeight: PropTypes.bool,
  /** use large/fat row in list */
  isLargeRow: PropTypes.bool,
  /** optional skeleton to be rendered while loading data */
  isLoading: PropTypes.bool,
  /** i18n strings */
  i18n: PropTypes.shape({
    searchPlaceHolderText: PropTypes.string,
    pageOfPagesText: PropTypes.func,
    expand: PropTypes.string,
    close: PropTypes.string
  }),
  /** pageSize */
  pageSize: PropTypes.string,
  /** callback function returned a modified list */
  onListUpdated: PropTypes.func,
  /** optionally renders SimplePagination at the bottom of the list */
  hasPagination: PropTypes.bool,
  /** Optional callback when a item is selected.
   * OnSelect(itemId, parentItemId)
   */
  onSelect: PropTypes.func,
  testId: PropTypes.string,
  /** content shown if list is empty on search */
  emptySearchState: PropTypes.oneOfType([PropTypes.node, PropTypes.string])
};
var defaultProps = {
  buttons: [],
  editingStyle: null,
  hasSearch: false,
  onListUpdated: function onListUpdated() {},
  i18n: {
    searchPlaceHolderText: 'Enter a value',
    pageOfPagesText: function pageOfPagesText(page) {
      return "Page ".concat(page);
    },
    items: '%d items'
  },
  isLargeRow: false,
  isFullHeight: false,
  isLoading: false,
  pageSize: null,
  hasPagination: true,
  onSelect: null,
  testId: 'simple-list',
  emptySearchState: 'No results found'
};
var SimpleList = function SimpleList(_ref) {
  var buttons = _ref.buttons,
    editingStyle = _ref.editingStyle,
    hasSearch = _ref.hasSearch,
    i18n = _ref.i18n,
    isFullHeight = _ref.isFullHeight,
    isLargeRow = _ref.isLargeRow,
    isLoading = _ref.isLoading,
    items = _ref.items,
    onListUpdated = _ref.onListUpdated,
    pageSize = _ref.pageSize,
    hasPagination = _ref.hasPagination,
    onSelect = _ref.onSelect,
    title = _ref.title,
    testId = _ref.testId,
    emptySearchState = _ref.emptySearchState;
  var mergedI18n = useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  }, [i18n]);
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    selectedIds = _useState2[0],
    setSelectedIds = _useState2[1];
  var _useState3 = useState(''),
    _useState4 = _slicedToArray(_useState3, 2),
    searchValue = _useState4[0],
    setSearchValue = _useState4[1];
  var _useState5 = useState(items),
    _useState6 = _slicedToArray(_useState5, 2),
    filteredItems = _useState6[0],
    setFilteredItems = _useState6[1];
  var _useState7 = useState([]),
    _useState8 = _slicedToArray(_useState7, 2),
    editModeSelectedIds = _useState8[0],
    setEditModeSelectedIds = _useState8[1];
  var _useState9 = useState(1),
    _useState10 = _slicedToArray(_useState9, 2),
    currentPageNumber = _useState10[0],
    setCurrentPageNumber = _useState10[1];
  var numberOfItems = filteredItems.length;
  var rowPerPage = useMemo(function () {
    if (!hasPagination) {
      return numberOfItems;
    }
    switch (pageSize) {
      case 'sm':
        return 5;
      case 'lg':
        return 10;
      case 'xl':
      default:
        return 20;
    }
  }, [hasPagination, numberOfItems, pageSize]);
  var _useState11 = useState(filteredItems.slice(0, rowPerPage)),
    _useState12 = _slicedToArray(_useState11, 2),
    itemsToShow = _useState12[0],
    setItemsToShow = _useState12[1];
  var handleSearch = useCallback(function (searchTerm) {
    setSearchValue(searchTerm);
    var searchFilteredItems = items.filter(function (item) {
      if (item.content.value !== '' && item.content.value !== undefined) {
        if (typeof item.content.secondaryValue === 'string' && item.content.secondaryValue !== '') {
          return item.content.value.toLowerCase().search(searchTerm.toLowerCase()) !== -1 || item.content.secondaryValue.toLowerCase().search(searchTerm.toLowerCase()) !== -1;
        }
        return item.content.value.toLowerCase().search(searchTerm.toLowerCase()) !== -1;
      }
      return false;
    });
    setFilteredItems(searchFilteredItems);
    setSearchValue(searchTerm);
    if (pageSize !== null) {
      setItemsToShow(searchFilteredItems.slice(0, rowPerPage));
    }
  }, [items, pageSize, rowPerPage]);
  var onPage = useCallback(function (page) {
    var rowUpperLimit = page * rowPerPage;
    var currentItemsOnPage = filteredItems.slice(rowUpperLimit - rowPerPage, rowUpperLimit);
    setCurrentPageNumber(page);
    setItemsToShow(currentItemsOnPage);
  }, [filteredItems, rowPerPage]);
  var maxPage = Math.ceil(numberOfItems / rowPerPage);

  /**
   * When the items array updates, make sure to update the filteredItems, but also re-apply
   * search values if there were any.
   */
  useEffect(function () {
    setFilteredItems(items);
    if (searchValue) {
      handleSearch(searchValue);
    }
  }, [items, handleSearch, searchValue]);

  /**
   * to maintain the correct page and items from that page, we must update the
   * itemsToShow array based on the current page and the number of rows shown based on
   * the pageSize prop.
   */
  useEffect(function () {
    var startIndex = (currentPageNumber - 1) * rowPerPage;
    setItemsToShow(filteredItems.slice(startIndex, startIndex + rowPerPage));
  }, [currentPageNumber, filteredItems, rowPerPage]);

  /**
   * If we were on a higher page and the number of items drop, we need to ensure we
   * reset to the first page when the number of items drops below our previous max page.
   */
  useEffect(function () {
    if (currentPageNumber > maxPage) {
      onPage(1);
    }
  }, [currentPageNumber, maxPage, onPage, pageSize]);
  var handleSelect = function handleSelect(id, parentId) {
    if (editingStyle) {
      setEditModeSelectedIds(handleEditModeSelect(items, editModeSelectedIds, id, parentId));
    } else {
      setSelectedIds(selectedIds.indexOf(id) !== -1 ? selectedIds.filter(function (item) {
        return item !== id;
      }) : [].concat(_toConsumableArray(selectedIds), [id]));
      if (onSelect) {
        onSelect(id, parentId);
      }
    }
  };
  var onItemMoved = function onItemMoved(dragId, hoverId, target) {
    var updatedList;
    if (editModeSelectedIds.length > 0 && editModeSelectedIds.find(function (selectionId) {
      return selectionId === dragId;
    })) {
      updatedList = moveItemsInList(items, editModeSelectedIds, hoverId, target);
    } else {
      updatedList = moveItemsInList(items, [dragId], hoverId, target);
    }
    onListUpdated(updatedList);
    setFilteredItems(updatedList);
  };
  return /*#__PURE__*/React__default.createElement(List, {
    title: title,
    search: hasSearch ? {
      value: searchValue,
      onChange: function onChange(evt) {
        handleSearch(evt.target.value);
      }
    } : null,
    buttons: buttons,
    i18n: mergedI18n,
    isFullHeight: isFullHeight,
    items: pageSize !== null ? itemsToShow : filteredItems,
    pagination: hasPagination ? {
      page: currentPageNumber,
      onPage: onPage,
      maxPage: maxPage,
      pageOfPagesText: function pageOfPagesText(page) {
        return mergedI18n.pageOfPagesText(page);
      }
    } : null,
    selectedIds: editingStyle ? editModeSelectedIds : selectedIds,
    handleSelect: handleSelect,
    isFiltering: !!searchValue,
    isLargeRow: isLargeRow,
    isLoading: isLoading,
    editingStyle: editingStyle,
    onItemMoved: onItemMoved,
    testId: testId,
    emptySearchState: emptySearchState
  });
};
SimpleList.propTypes = propTypes;
SimpleList.defaultProps = defaultProps;
SimpleList.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "SimpleList",
  "props": {
    "buttons": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "description": "action buttons on right side of list title",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "node"
        }
      },
      "required": false
    },
    "editingStyle": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "list editing style",
      "type": {
        "name": "enum",
        "value": [{
          "value": "EditingStyle.Single",
          "computed": true
        }, {
          "value": "EditingStyle.Multiple",
          "computed": true
        }, {
          "value": "EditingStyle.SingleNesting",
          "computed": true
        }, {
          "value": "EditingStyle.MultipleNesting",
          "computed": true
        }]
      },
      "required": false
    },
    "hasSearch": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "use search with default behavior",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "onListUpdated": {
      "defaultValue": {
        "value": "() => {}",
        "computed": false
      },
      "description": "callback function returned a modified list",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  searchPlaceHolderText: 'Enter a value',\n  pageOfPagesText: (page) => `Page ${page}`,\n  items: '%d items',\n}",
        "computed": false
      },
      "description": "i18n strings",
      "type": {
        "name": "shape",
        "value": {
          "searchPlaceHolderText": {
            "name": "string",
            "required": false
          },
          "pageOfPagesText": {
            "name": "func",
            "required": false
          },
          "expand": {
            "name": "string",
            "required": false
          },
          "close": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "isLargeRow": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "use large/fat row in list",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "isFullHeight": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "use full height in list",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "isLoading": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "optional skeleton to be rendered while loading data",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "pageSize": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "pageSize",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "hasPagination": {
      "defaultValue": {
        "value": "true",
        "computed": false
      },
      "description": "optionally renders SimplePagination at the bottom of the list",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "onSelect": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Optional callback when a item is selected.\nOnSelect(itemId, parentItemId)",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'simple-list'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "emptySearchState": {
      "defaultValue": {
        "value": "'No results found'",
        "computed": false
      },
      "description": "content shown if list is empty on search",
      "type": {
        "name": "union",
        "value": [{
          "name": "node"
        }, {
          "name": "string"
        }]
      },
      "required": false
    },
    "title": {
      "description": "list title",
      "type": {
        "name": "string"
      },
      "required": true
    },
    "items": {
      "description": "data source of list items",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "shape",
          "value": {
            "id": {
              "name": "string",
              "required": false
            },
            "content": {
              "name": "shape",
              "value": {
                "value": {
                  "name": "string",
                  "required": false
                },
                "icon": {
                  "name": "node",
                  "required": false
                }
              },
              "required": false
            },
            "children": {
              "name": "arrayOf",
              "value": {
                "name": "any"
              },
              "required": false
            },
            "isSelectable": {
              "name": "bool",
              "required": false
            }
          }
        }
      },
      "required": true
    }
  }
};
var SimpleList$1 = SimpleList;

export { SimpleList$1 as default };
