import _extends from "@babel/runtime/helpers/extends";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

/* eslint-disable react/forbid-prop-types */
import React, { useEffect, useImperativeHandle, useMemo } from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import { useTable, useSortBy, useRowSelect, usePagination, useMountedLayoutEffect, useFilters } from "react-table";
import getClasses from "./styles";
import Pagination from "./Pagination";
import Checkbox from "../Checkbox";
import SortIcon from "./SortIcon";

var mapRowsToIds = function mapRowsToIds(rows) {
  return Object.keys(rows).map(Number);
};

var DataTable = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var data = props.data,
      columns = props.columns,
      onSelectedRowsChange = props.onSelectedRowsChange,
      filters = props.filters,
      className = props.className,
      initialSortBy = props.initialSortBy,
      onFilterRows = props.onFilterRows,
      disableSelection = props.disableSelection;
  var classes = getClasses({
    disableSelection: disableSelection
  });
  var sortBy = useMemo(function () {
    return [initialSortBy];
  }, [initialSortBy]);

  var _useTable = useTable(_objectSpread({
    columns: columns,
    data: data
  }, initialSortBy && {
    initialState: {
      sortBy: sortBy
    }
  }), useFilters, useSortBy, usePagination, useRowSelect, function (hooks) {
    if (!disableSelection) {
      hooks.visibleColumns.push(function (visibleColumns) {
        return [{
          id: "selection",
          Header: function Header(_ref) {
            var getToggleAllRowsSelectedProps = _ref.getToggleAllRowsSelectedProps;
            return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Checkbox, getToggleAllRowsSelectedProps()));
          },
          Cell: function Cell(_ref2) {
            var row = _ref2.row;
            return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Checkbox, row.getToggleRowSelectedProps()));
          },
          className: classes.checkCell
        }].concat(_toConsumableArray(visibleColumns));
      });
    }
  }),
      getTableProps = _useTable.getTableProps,
      getTableBodyProps = _useTable.getTableBodyProps,
      headerGroups = _useTable.headerGroups,
      page = _useTable.page,
      prepareRow = _useTable.prepareRow,
      gotoPage = _useTable.gotoPage,
      rows = _useTable.rows,
      setAllFilters = _useTable.setAllFilters,
      filteredRowsById = _useTable.filteredRowsById,
      toggleAllRowsSelected = _useTable.toggleAllRowsSelected,
      toggleRowSelected = _useTable.toggleRowSelected,
      _useTable$state = _useTable.state,
      pageIndex = _useTable$state.pageIndex,
      pageSize = _useTable$state.pageSize,
      selectedRowIds = _useTable$state.selectedRowIds;

  useImperativeHandle(ref, function () {
    return {
      selectRows: function selectRows(ids) {
        return ids.forEach(function (id) {
          return toggleRowSelected(id, true);
        });
      },
      deselectRows: function deselectRows(ids) {
        return ids.forEach(function (id) {
          return toggleRowSelected(id, false);
        });
      },
      toggleAllRowsSelected: toggleAllRowsSelected
    };
  });
  useEffect(function () {
    var reactTableFilters = Object.keys(filters).map(function (id) {
      return {
        id: id,
        value: filters[id]
      };
    });
    setAllFilters(reactTableFilters);
  }, [filters]);
  useMountedLayoutEffect(function () {
    if (typeof onSelectedRowsChange === "function") {
      var ids = mapRowsToIds(selectedRowIds);
      onSelectedRowsChange(ids);
    }
  }, [onSelectedRowsChange, selectedRowIds]);
  useMountedLayoutEffect(function () {
    if (typeof onFilterRows === "function") {
      var ids = mapRowsToIds(filteredRowsById);
      onFilterRows(ids);
    }
  }, [onFilterRows, filteredRowsById]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: classnames(classes.container, className)
  }, /*#__PURE__*/React.createElement("table", _extends({
    className: classes.table
  }, getTableProps()), /*#__PURE__*/React.createElement("thead", null, headerGroups.map(function (headerGroup) {
    return /*#__PURE__*/React.createElement("tr", headerGroup.getHeaderGroupProps(), headerGroup.headers.map(function (column) {
      return /*#__PURE__*/React.createElement("th", _extends({
        className: classnames(_defineProperty({}, classes.sortable, column.canSort), column.className)
      }, column.getHeaderProps(column.getSortByToggleProps({
        style: {
          "--header-text-align": column.headerAlign || column.align
        }
      }))), column.render("Header"), column.canSort && /*#__PURE__*/React.createElement(SortIcon, {
        className: classes.sortIcon,
        activeDown: column.isSorted && column.isSortedDesc,
        activeUp: column.isSorted && !column.isSortedDesc
      }));
    }));
  })), /*#__PURE__*/React.createElement("tbody", getTableBodyProps(), page.map(function (row) {
    prepareRow(row);
    return /*#__PURE__*/React.createElement("tr", _extends({}, row.getRowProps(), {
      onClick: !disableSelection ? function () {
        return row.toggleRowSelected(!row.isSelected);
      } : undefined
    }), row.cells.map(function (cell) {
      var _classnames2;

      return /*#__PURE__*/React.createElement("td", _extends({
        className: classnames((_classnames2 = {}, _defineProperty(_classnames2, classes.sortable, cell.column.canSort), _defineProperty(_classnames2, classes.selected, !disableSelection ? cell.row.isSelected : false), _classnames2), cell.column.className)
      }, cell.getCellProps({
        style: {
          "--body-text-align": cell.column.bodyAlign || cell.column.align
        }
      })), cell.render("Cell"));
    }));
  })))), /*#__PURE__*/React.createElement(Pagination, {
    page: pageIndex,
    onPageChange: gotoPage,
    pageSize: pageSize,
    total: rows.length
  }));
});
DataTable.propTypes = {
  columns: PropTypes.array.isRequired,
  data: PropTypes.array.isRequired,
  onSelectedRowsChange: PropTypes.func,
  onFilterRows: PropTypes.func,
  filters: PropTypes.object,
  initialSortBy: PropTypes.shape({
    id: PropTypes.string.isRequired,
    desc: PropTypes.bool
  }),
  disableSelection: PropTypes.bool
};
DataTable.defaultProps = {
  filters: {},
  disableSelection: false
};
export default DataTable;