import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import isEqual from '../../../node_modules/lodash-es/isEqual.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.find.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.array.sort.js';
import 'core-js/modules/es.array.splice.js';
import 'core-js/modules/es.function.name.js';
import 'core-js/modules/es.object.assign.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/web.dom-collections.for-each.js';
import React__default, { useCallback, useState, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import update from 'immutability-helper';
import Button from '../../Button/Button.js';
import ComposedModal from '../../ComposedModal/ComposedModal.js';
import { settings } from '../../../constants/Settings.js';
import { TableColumnsPropTypes, TableSortPropType } from '../TablePropTypes.js';
import { DragAndDrop } from '../../../utils/DragAndDropUtils.js';
import { TableMultiSortRow } from './TableMultiSortRow.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 iotPrefix = settings.iotPrefix,
  prefix = settings.prefix;
var propTypes = {
  columns: TableColumnsPropTypes.isRequired,
  ordering: PropTypes.arrayOf(PropTypes.shape({
    columnId: PropTypes.string.isRequired,
    /* Visibility of column in table, defaults to false */
    isHidden: PropTypes.bool
  })).isRequired,
  actions: PropTypes.shape({
    onAddMultiSortColumn: PropTypes.func,
    onRemoveMultiSortColumn: PropTypes.func,
    onSaveMultiSortColumns: PropTypes.func,
    onCancelMultiSortColumns: PropTypes.func,
    onClearMultiSortColumns: PropTypes.func
  }).isRequired,
  sort: PropTypes.oneOfType([TableSortPropType, PropTypes.arrayOf(TableSortPropType)]).isRequired,
  showMultiSortModal: PropTypes.bool,
  i18n: PropTypes.shape({
    multiSortModalTitle: PropTypes.string,
    multiSortModalPrimaryLabel: PropTypes.string,
    multiSortModalSecondaryLabel: PropTypes.string,
    multiSortModalClearLabel: PropTypes.string,
    multiSortSelectColumnLabel: PropTypes.string,
    multiSortSelectColumnSortByTitle: PropTypes.string,
    multiSortSelectColumnThenByTitle: PropTypes.string,
    multiSortDirectionLabel: PropTypes.string,
    multiSortDirectionTitle: PropTypes.string,
    multiSortAddColumn: PropTypes.string,
    multiSortRemoveColumn: PropTypes.string,
    multiSortAscending: PropTypes.string,
    multiSortDescending: PropTypes.string,
    multiSortCloseModal: PropTypes.string,
    multiSortOpenMenu: PropTypes.string,
    multiSortCloseMenu: PropTypes.string,
    multiSortDragHandle: PropTypes.string
  }),
  testId: PropTypes.string
};
var defaultProps = {
  showMultiSortModal: false,
  i18n: {
    multiSortModalTitle: 'Select columns to sort',
    multiSortModalPrimaryLabel: 'Sort',
    multiSortModalSecondaryLabel: 'Cancel',
    multiSortModalClearLabel: 'Clear sorting',
    multiSortSelectColumnLabel: 'Select a column',
    multiSortSelectColumnSortByTitle: 'Sort by',
    multiSortSelectColumnThenByTitle: 'Then by',
    multiSortDirectionLabel: 'Select a direction',
    multiSortDirectionTitle: 'Sort order',
    multiSortAddColumn: 'Add column',
    multiSortRemoveColumn: 'Remove column',
    multiSortAscending: 'Ascending',
    multiSortDescending: 'Descending',
    multiSortCloseModal: 'Close',
    multiSortDragHandle: 'Drag handle'
  },
  testId: 'multi-sort-modal'
};

/**
 * Simple helper function to turn the sort object into an array and filter empty values from it
 * @param {Array|Object} sort A sort object or an array of sort objects
 * @returns Array
 */
var cleanSortArray = function cleanSortArray(sort) {
  var sortArray = Array.isArray(sort) ? sort : sort !== undefined ? [sort] : [];
  return sortArray.filter(function (_ref) {
    var columnId = _ref.columnId;
    return columnId;
  });
};
var TableMultiSortModal = function TableMultiSortModal(_ref2) {
  var columns = _ref2.columns,
    ordering = _ref2.ordering,
    sort = _ref2.sort,
    actions = _ref2.actions,
    showMultiSortModal = _ref2.showMultiSortModal,
    i18n = _ref2.i18n,
    testId = _ref2.testId;
  var onAddMultiSortColumn = actions.onAddMultiSortColumn,
    onRemoveMultiSortColumn = actions.onRemoveMultiSortColumn,
    onSaveMultiSortColumns = actions.onSaveMultiSortColumns,
    onCancelMultiSortColumns = actions.onCancelMultiSortColumns,
    onClearMultiSortColumns = actions.onClearMultiSortColumns;
  var sortHelper = useCallback(function () {
    var sortArray = cleanSortArray(sort);
    if (!sortArray.length) {
      return [{
        columnId: '',
        direction: 'ASC'
      }];
    }
    return sortArray;
  }, [sort]);
  var _useState = useState(sortHelper),
    _useState2 = _slicedToArray(_useState, 2),
    selectedMultiSortColumns = _useState2[0],
    setSelectedMultiSortColumns = _useState2[1];
  useEffect(function () {
    setSelectedMultiSortColumns(sortHelper);
  }, [sort, sortHelper]);
  var sortDirections = useMemo(function () {
    return [{
      id: 'ASC',
      label: i18n.multiSortAscending
    }, {
      id: 'DESC',
      label: i18n.multiSortDescending
    }];
  }, [i18n.multiSortAscending, i18n.multiSortDescending]);
  var handleSelectMultiSortColumn = function handleSelectMultiSortColumn(index) {
    return function (event) {
      var columnId = event.target.value;
      setSelectedMultiSortColumns(function (prev) {
        var currentItem = prev[index];
        return Object.assign([], prev, _defineProperty({}, index, _objectSpread(_objectSpread({}, currentItem), {}, {
          columnId: columnId
        })));
      });
    };
  };
  var handleSelectMultiSortColumnDirection = function handleSelectMultiSortColumnDirection(index) {
    return function (event) {
      var direction = event.target.value;
      setSelectedMultiSortColumns(function (prev) {
        var currentItem = prev[index];
        return Object.assign([], prev, _defineProperty({}, index, _objectSpread(_objectSpread({}, currentItem), {}, {
          direction: direction
        })));
      });
    };
  };
  var multiSortColumns = useMemo(function () {
    return columns.filter(function (_ref3) {
      var id = _ref3.id,
        isSortable = _ref3.isSortable;
      var orderCol = ordering.find(function (_ref4) {
        var columnId = _ref4.columnId;
        return columnId === id;
      });
      return isSortable && !orderCol.isHidden;
    }).map(function (col) {
      var columnAlreadySorted = selectedMultiSortColumns.find(function (_ref5) {
        var columnId = _ref5.columnId;
        return columnId === col.id;
      }) !== undefined;
      return {
        id: col.id,
        name: col.name,
        disabled: columnAlreadySorted
      };
    });
  }, [columns, ordering, selectedMultiSortColumns]);
  var getInitialSelectedColumn = function getInitialSelectedColumn(columnId) {
    var selectedColumn = columns.find(function (col) {
      return col.id === columnId;
    });
    return selectedColumn || multiSortColumns.filter(function (col) {
      return !col.disabled;
    })[0];
  };
  var getInitialSelectedDirection = function getInitialSelectedDirection(direction) {
    var selectedDirection = sortDirections.find(function (dir) {
      return dir.id === direction;
    });
    return selectedDirection || sortDirections[0];
  };
  var handleAddMultiSortColumn = function handleAddMultiSortColumn(index) {
    return function () {
      setSelectedMultiSortColumns(function (prev) {
        var _multiSortColumns$fil2;
        var clone = _toConsumableArray(prev);
        var nextColumnIndex = 0;
        // If the default column is in the first position, set it before adding the next column
        if (clone.length === 1 && Object.keys(clone[0]).length === 0) {
          var _multiSortColumns$fil;
          clone.splice(index, 1, {
            columnId: (_multiSortColumns$fil = multiSortColumns.filter(function (col) {
              return !col.disabled;
            })[nextColumnIndex]) === null || _multiSortColumns$fil === void 0 ? void 0 : _multiSortColumns$fil.id,
            direction: 'ASC'
          });
          nextColumnIndex = 1;
        }
        clone.splice(index + 1, 0, {
          columnId: (_multiSortColumns$fil2 = multiSortColumns.filter(function (col) {
            return !col.disabled;
          })[nextColumnIndex]) === null || _multiSortColumns$fil2 === void 0 ? void 0 : _multiSortColumns$fil2.id,
          direction: 'ASC'
        });
        return clone;
      });
      onAddMultiSortColumn(index);
    };
  };
  var handleRemoveMultiSortColumn = function handleRemoveMultiSortColumn(index) {
    return function () {
      setSelectedMultiSortColumns(function (prev) {
        return prev.filter(function (c, i) {
          return i !== index;
        });
      });
      onRemoveMultiSortColumn(index);
    };
  };
  var handleSaveMultiSortColumns = function handleSaveMultiSortColumns() {
    // if empty strings were passed for columnId or direction
    // the dropdown will show the first available column and direction,
    // but if they save without performing a change, the initial state
    // is empty, so we perform a check to ensure the defaults are saved
    var defaulted = selectedMultiSortColumns.map(function (_ref6) {
      var columnId = _ref6.columnId,
        direction = _ref6.direction;
      var column = getInitialSelectedColumn(columnId);
      var dir = getInitialSelectedDirection(direction);
      return {
        columnId: columnId || column.id,
        direction: direction || dir.id
      };
    });
    if (!isEqual(selectedMultiSortColumns, defaulted)) {
      setSelectedMultiSortColumns(defaulted);
    }
    onSaveMultiSortColumns(defaulted);
  };
  var handleCancelMultiSortColumns = function handleCancelMultiSortColumns() {
    setSelectedMultiSortColumns(cleanSortArray(sort));
    onCancelMultiSortColumns();
  };
  var handleClearMultiSortColumns = function handleClearMultiSortColumns() {
    setSelectedMultiSortColumns([]);
    onClearMultiSortColumns();
  };
  var onMoveRow = useCallback(function (dragIndex, hoverIndex) {
    setSelectedMultiSortColumns(function (prev) {
      var row = prev[dragIndex];
      return update(prev, {
        $splice: [[dragIndex, 1], [hoverIndex, 0, row]]
      });
    });
  }, []);
  return /*#__PURE__*/React__default.createElement(ComposedModal, {
    selectorPrimaryFocus: ".".concat(prefix, "--modal-header"),
    testId: testId,
    className: "".concat(iotPrefix, "--table-multi-sort-modal"),
    header: {
      title: i18n.multiSortModalTitle
    },
    iconDescription: i18n.multiSortCloseModal,
    onClose: handleCancelMultiSortColumns,
    footer: /*#__PURE__*/React__default.createElement("div", {
      className: "".concat(iotPrefix, "--table-multi-sort-modal__footer")
    }, /*#__PURE__*/React__default.createElement(Button, {
      kind: "ghost",
      onClick: handleClearMultiSortColumns,
      testId: "".concat(testId, "-modal-clear-button")
    }, i18n.multiSortModalClearLabel), /*#__PURE__*/React__default.createElement("div", null), /*#__PURE__*/React__default.createElement(Button, {
      kind: "secondary",
      onClick: handleCancelMultiSortColumns,
      testId: "".concat(testId, "-modal-secondary-button")
    }, i18n.multiSortModalSecondaryLabel), /*#__PURE__*/React__default.createElement(Button, {
      kind: "primary",
      onClick: handleSaveMultiSortColumns,
      testId: "".concat(testId, "-modal-primary-button"),
      "data-modal-primary-focus": true
    }, i18n.multiSortModalPrimaryLabel)),
    open: showMultiSortModal
  }, /*#__PURE__*/React__default.createElement(DragAndDrop, null, selectedMultiSortColumns.map(function (_ref7, index) {
    var columnId = _ref7.columnId,
      direction = _ref7.direction;
    var defaultColumn = getInitialSelectedColumn(columnId);
    var defaultDirection = getInitialSelectedDirection(direction);
    return /*#__PURE__*/React__default.createElement(TableMultiSortRow, {
      key: "".concat(columnId, "-").concat(direction),
      columnId: columnId || (defaultColumn === null || defaultColumn === void 0 ? void 0 : defaultColumn.id),
      defaultColumnId: defaultColumn === null || defaultColumn === void 0 ? void 0 : defaultColumn.id,
      defaultDirectionId: defaultDirection === null || defaultDirection === void 0 ? void 0 : defaultDirection.id,
      i18n: i18n,
      index: index,
      multiSortColumns: multiSortColumns,
      numSelectedColumns: selectedMultiSortColumns === null || selectedMultiSortColumns === void 0 ? void 0 : selectedMultiSortColumns.length,
      onAddMultiSortColumn: handleAddMultiSortColumn(index),
      onMoveRow: onMoveRow,
      onRemoveMultiSortColumn: handleRemoveMultiSortColumn(index),
      onSelectMultiSortColumn: handleSelectMultiSortColumn(index),
      onSelectMultiSortColumnDirection: handleSelectMultiSortColumnDirection(index),
      sortDirections: sortDirections,
      testId: testId
    });
  })));
};
TableMultiSortModal.propTypes = propTypes;
TableMultiSortModal.defaultProps = defaultProps;
TableMultiSortModal.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "TableMultiSortModal",
  "props": {
    "showMultiSortModal": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  multiSortModalTitle: 'Select columns to sort',\n  multiSortModalPrimaryLabel: 'Sort',\n  multiSortModalSecondaryLabel: 'Cancel',\n  multiSortModalClearLabel: 'Clear sorting',\n  multiSortSelectColumnLabel: 'Select a column',\n  multiSortSelectColumnSortByTitle: 'Sort by',\n  multiSortSelectColumnThenByTitle: 'Then by',\n  multiSortDirectionLabel: 'Select a direction',\n  multiSortDirectionTitle: 'Sort order',\n  multiSortAddColumn: 'Add column',\n  multiSortRemoveColumn: 'Remove column',\n  multiSortAscending: 'Ascending',\n  multiSortDescending: 'Descending',\n  multiSortCloseModal: 'Close',\n  multiSortDragHandle: 'Drag handle',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "multiSortModalTitle": {
            "name": "string",
            "required": false
          },
          "multiSortModalPrimaryLabel": {
            "name": "string",
            "required": false
          },
          "multiSortModalSecondaryLabel": {
            "name": "string",
            "required": false
          },
          "multiSortModalClearLabel": {
            "name": "string",
            "required": false
          },
          "multiSortSelectColumnLabel": {
            "name": "string",
            "required": false
          },
          "multiSortSelectColumnSortByTitle": {
            "name": "string",
            "required": false
          },
          "multiSortSelectColumnThenByTitle": {
            "name": "string",
            "required": false
          },
          "multiSortDirectionLabel": {
            "name": "string",
            "required": false
          },
          "multiSortDirectionTitle": {
            "name": "string",
            "required": false
          },
          "multiSortAddColumn": {
            "name": "string",
            "required": false
          },
          "multiSortRemoveColumn": {
            "name": "string",
            "required": false
          },
          "multiSortAscending": {
            "name": "string",
            "required": false
          },
          "multiSortDescending": {
            "name": "string",
            "required": false
          },
          "multiSortCloseModal": {
            "name": "string",
            "required": false
          },
          "multiSortOpenMenu": {
            "name": "string",
            "required": false
          },
          "multiSortCloseMenu": {
            "name": "string",
            "required": false
          },
          "multiSortDragHandle": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'multi-sort-modal'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "columns": {
      "description": "",
      "type": {
        "name": "custom",
        "raw": "TableColumnsPropTypes.isRequired"
      },
      "required": false
    },
    "ordering": {
      "description": "",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "shape",
          "value": {
            "columnId": {
              "name": "string",
              "required": true
            },
            "isHidden": {
              "name": "bool",
              "required": false
            }
          }
        }
      },
      "required": true
    },
    "actions": {
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "onAddMultiSortColumn": {
            "name": "func",
            "required": false
          },
          "onRemoveMultiSortColumn": {
            "name": "func",
            "required": false
          },
          "onSaveMultiSortColumns": {
            "name": "func",
            "required": false
          },
          "onCancelMultiSortColumns": {
            "name": "func",
            "required": false
          },
          "onClearMultiSortColumns": {
            "name": "func",
            "required": false
          }
        }
      },
      "required": true
    },
    "sort": {
      "description": "",
      "type": {
        "name": "union",
        "value": [{
          "name": "custom",
          "raw": "TableSortPropType"
        }, {
          "name": "arrayOf",
          "value": {
            "name": "custom",
            "raw": "TableSortPropType"
          }
        }]
      },
      "required": true
    }
  }
};
var TableMultiSortModal$1 = TableMultiSortModal;

export { TableMultiSortModal$1 as default };
