var _excluded = ["id", "headers", "testPrefix", "rowReverse", "enableColumnReordering"],
  _excluded2 = ["groups", "size", "side", "flex", "enableColumnReordering"],
  _excluded3 = ["table", "testPrefix", "enableColumnReordering"];
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 _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; }
import React, { memo, useState, useMemo, useCallback } from "react";
import styled from "styled-components";
import { DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors } from "@dnd-kit/core";
import { SortableContext, horizontalListSortingStrategy, arrayMove } from "@dnd-kit/sortable";
import { restrictToHorizontalAxis } from "@dnd-kit/modifiers";
import Flex from "../../../templates/flex";
import { useTableState } from "../../provider";
import Cell from "./cell";
import { Handler } from "./resizeHandler";
import DragOverlay from "./dragOverlay";
var rerenderSelector = function rerenderSelector(state) {
  var columns = state.allColumns || [];
  return {
    sizing: state.columnSizing,
    expanded: state.expanded,
    columnVisibility: state.columnVisibility,
    selectedRows: state.selectedRows,
    grouping: state.grouping,
    columnsCount: columns.length,
    columnsFilters: columns.map(function (_ref) {
      var _columnDef$meta;
      var columnDef = _ref.columnDef;
      return columnDef == null || (_columnDef$meta = columnDef.meta) == null || (_columnDef$meta = _columnDef$meta.filter) == null ? void 0 : _columnDef$meta.options;
    })
  };
};
var _HeaderGroup = function HeaderGroup(_ref2) {
  var id = _ref2.id,
    headers = _ref2.headers,
    testPrefix = _ref2.testPrefix,
    rowReverse = _ref2.rowReverse,
    enableColumnReordering = _ref2.enableColumnReordering,
    rest = _objectWithoutPropertiesLoose(_ref2, _excluded);
  var columnIds = useMemo(function () {
    return headers.map(function (h) {
      return h.column.id;
    });
  }, [headers]);
  var content = /*#__PURE__*/React.createElement(Flex, {
    id: id,
    "data-testid": "netdata-table-headRow" + testPrefix,
    flex: true,
    background: "tableRowBg",
    rowReverse: rowReverse
  }, headers.map(function (header, index) {
    return /*#__PURE__*/React.createElement(Cell, _extends({
      key: header.id,
      index: index
    }, rest, {
      header: header,
      testPrefix: testPrefix,
      hasSubheaders: !!header.subHeaders.length,
      enableColumnReordering: enableColumnReordering && header.column.columnDef.enableReordering !== false
    }), !!header.subHeaders.length && /*#__PURE__*/React.createElement(_HeaderGroup, _extends({
      headers: header.subHeaders,
      id: header.id,
      key: header.id
    }, rest, {
      enableColumnReordering: enableColumnReordering,
      isSubheader: true
    })));
  }));
  if (!enableColumnReordering) {
    return content;
  }
  return /*#__PURE__*/React.createElement(SortableContext, {
    items: columnIds,
    strategy: horizontalListSortingStrategy
  }, content);
};
var HeaderGroups = function HeaderGroups(_ref3) {
  var groups = _ref3.groups,
    size = _ref3.size,
    side = _ref3.side,
    _ref3$flex = _ref3.flex,
    flex = _ref3$flex === void 0 ? "grow" : _ref3$flex,
    enableColumnReordering = _ref3.enableColumnReordering,
    rest = _objectWithoutPropertiesLoose(_ref3, _excluded2);
  if (!groups[0].headers.length) return null;
  return /*#__PURE__*/React.createElement(Flex, _extends({
    position: side ? "sticky" : "relative"
  }, side === "right" ? {
    right: 0,
    border: {
      side: "left"
    }
  } : {
    left: 0,
    border: {
      side: "right"
    }
  }, {
    zIndex: side ? 11 : undefined,
    width: size + "px",
    flex: flex,
    column: true
  }), /*#__PURE__*/React.createElement(_HeaderGroup, _extends({
    headers: groups[0].headers,
    id: groups[0].id,
    key: groups[0].id
  }, rest, {
    enableColumnReordering: enableColumnReordering
  })));
};
var HeaderRow = styled(Flex).withConfig({
  displayName: "header__HeaderRow",
  componentId: "sc-7c5nnc-0"
})(["", "{display:none;}&:hover ", "{display:block;}&:hover .drag-handle{opacity:1;}"], Handler, Handler);
var BodyHeader = /*#__PURE__*/memo(function (_ref4) {
  var table = _ref4.table,
    testPrefix = _ref4.testPrefix,
    enableColumnReordering = _ref4.enableColumnReordering,
    rest = _objectWithoutPropertiesLoose(_ref4, _excluded3);
  useTableState(rerenderSelector);
  var _useState = useState(null),
    activeId = _useState[0],
    setActiveId = _useState[1];
  var sensors = useSensors(useSensor(PointerSensor, {
    activationConstraint: {
      distance: 5
    }
  }), useSensor(KeyboardSensor));
  var activeColumn = useMemo(function () {
    if (!activeId) return null;
    return table.getColumn(activeId);
  }, [activeId, table]);
  var handleDragStart = useCallback(function (event) {
    setActiveId(event.active.id);
  }, []);
  var handleDragEnd = useCallback(function (event) {
    var active = event.active,
      over = event.over;
    setActiveId(null);
    if (!active || !over || active.id === over.id) return;
    var currentOrder = table.getState().columnOrder;
    var allColumns = table.getAllLeafColumns();
    var columnOrder = currentOrder.length > 0 ? currentOrder : allColumns.map(function (c) {
      return c.id;
    });
    var oldIndex = columnOrder.indexOf(active.id);
    var newIndex = columnOrder.indexOf(over.id);
    if (oldIndex === -1 || newIndex === -1) return;
    var activeColumn = table.getColumn(active.id);
    var overColumn = table.getColumn(over.id);
    if ((activeColumn == null ? void 0 : activeColumn.getIsPinned()) !== (overColumn == null ? void 0 : overColumn.getIsPinned())) return;
    var newOrder = arrayMove(columnOrder, oldIndex, newIndex);
    table.setColumnOrder(newOrder);
  }, [table]);
  var handleDragCancel = useCallback(function () {
    setActiveId(null);
  }, []);
  var headerContent = /*#__PURE__*/React.createElement(HeaderRow, {
    "data-testid": "netdata-table-head" + testPrefix,
    flex: true,
    border: {
      size: "1px",
      type: "solid",
      side: "bottom",
      color: "border"
    }
  }, /*#__PURE__*/React.createElement(HeaderGroups, _extends({
    groups: table.getLeftHeaderGroups(),
    side: "left",
    size: table.getLeftTotalSize(),
    testPrefix: testPrefix
  }, rest, {
    flex: false,
    table: table,
    enableColumnReordering: enableColumnReordering
  })), /*#__PURE__*/React.createElement(HeaderGroups, _extends({
    groups: table.getCenterHeaderGroups(),
    size: table.getCenterTotalSize(),
    testPrefix: testPrefix
  }, rest, {
    table: table,
    enableColumnReordering: enableColumnReordering
  })), /*#__PURE__*/React.createElement(HeaderGroups, _extends({
    groups: table.getRightHeaderGroups(),
    side: "right",
    size: table.getRightTotalSize(),
    testPrefix: testPrefix
  }, rest, {
    flex: false,
    table: table,
    enableColumnReordering: enableColumnReordering,
    rowReverse: true
  })));
  if (!enableColumnReordering) {
    return headerContent;
  }
  return /*#__PURE__*/React.createElement(DndContext, {
    sensors: sensors,
    collisionDetection: closestCenter,
    modifiers: [restrictToHorizontalAxis],
    onDragStart: handleDragStart,
    onDragEnd: handleDragEnd,
    onDragCancel: handleDragCancel
  }, headerContent, /*#__PURE__*/React.createElement(DragOverlay, {
    activeColumn: activeColumn
  }));
});
export default BodyHeader;