var _excluded = ["activationConstraint", "collisionDetection", "measuring", "modifiers"];
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; }
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); }
import React, { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { closestCenter, DragOverlay, DndContext, MouseSensor, TouchSensor, useSensor, useSensors, useDndMonitor, defaultDropAnimationSideEffects, MeasuringStrategy } from "@dnd-kit/core";
import { SortableContext } from "@dnd-kit/sortable";
import { defaultAnimateLayoutChanges, horizontalListSortingStrategy } from "@dnd-kit/sortable";
import { debounce } from "throttle-debounce";
import Flex from "../../../components/templates/flex";
import useNavigationScroll from "../hooks/useNavigationScroll";
import useNavigationArrows from "../hooks/useNavigationArrows";
import useOnTabsResize from "../hooks/useOnTabsResize";
import { mergeRefs } from "../../../utils";
import SortableItem from "./item";
import DefaultContainer from "./container";
import Arrow from "./arrow";
var dropAnimationConfig = {
  sideEffects: defaultDropAnimationSideEffects({
    styles: {
      active: {
        opacity: "0.5"
      }
    }
  })
};
export var BaseSortable = function BaseSortable(_ref) {
  var _ref$animateLayoutCha = _ref.animateLayoutChanges,
    animateLayoutChanges = _ref$animateLayoutCha === void 0 ? function (args) {
      return defaultAnimateLayoutChanges(_extends({}, args, {
        wasDragging: true
      }));
    } : _ref$animateLayoutCha,
    _ref$adjustScale = _ref.adjustScale,
    adjustScale = _ref$adjustScale === void 0 ? false : _ref$adjustScale,
    _ref$Container = _ref.Container,
    Container = _ref$Container === void 0 ? DefaultContainer : _ref$Container,
    _ref$dropAnimation = _ref.dropAnimation,
    dropAnimation = _ref$dropAnimation === void 0 ? dropAnimationConfig : _ref$dropAnimation,
    _ref$strategy = _ref.strategy,
    strategy = _ref$strategy === void 0 ? horizontalListSortingStrategy : _ref$strategy,
    _onDragEnd = _ref.onDragEnd,
    onTabClose = _ref.onTabClose,
    onResize = _ref.onResize,
    items = _ref.items,
    Item = _ref.Item,
    parentRef = _ref.parentRef,
    collapsed = _ref.collapsed,
    ref = _ref.ref;
  var _useState = useState(null),
    activeId = _useState[0],
    setActiveId = _useState[1];
  var getIndex = function getIndex(id) {
    return items.findIndex(function (item) {
      return item.id === id;
    });
  };
  var activeIndex = activeId !== null ? getIndex(activeId) : -1;
  var containerRef = useRef();
  useNavigationScroll(containerRef);
  var lastTabRef = useRef();
  var onTabsResize = useOnTabsResize(parentRef, containerRef, lastTabRef, onResize, [items.length]);
  var _useNavigationArrows = useNavigationArrows(containerRef, lastTabRef, items.length, collapsed),
    arrowLeft = _useNavigationArrows[0],
    arrowRight = _useNavigationArrows[1],
    onScroll = _useNavigationArrows[2];
  useEffect(function () {
    if (!containerRef.current) return;
    onTabsResize();
    var container = containerRef.current;
    var handlers = debounce(300, function () {
      onTabsResize();
      onScroll();
    });
    handlers();
    container.addEventListener("scroll", onScroll);
    window.addEventListener("resize", handlers);
    return function () {
      container.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", handlers);
    };
  }, [items.length, collapsed]);
  var scrollLeft = function scrollLeft(e) {
    e.preventDefault();
    containerRef.current.scrollTo({
      left: containerRef.current.scrollLeft - 100,
      behavior: "smooth"
    });
  };
  var scrollRight = function scrollRight(e) {
    e.preventDefault();
    containerRef.current.scrollTo({
      left: containerRef.current.scrollLeft + 100,
      behavior: "smooth"
    });
  };
  useDndMonitor({
    onDragStart: function onDragStart(_ref2) {
      var active = _ref2.active;
      if (!active || !active.data.current.navigationTab) return;
      setActiveId(active.id);
    },
    onDragEnd: function onDragEnd(_ref3) {
      var active = _ref3.active,
        over = _ref3.over;
      if (!active || !active.data.current.navigationTab) return;
      setActiveId(null);
      if (over && over.data.current.navigationTab) {
        var overIndex = getIndex(over.id);
        if (activeIndex !== overIndex) {
          _onDragEnd(activeIndex, overIndex);
        }
      }
    },
    onDragCancel: function onDragCancel() {
      return setActiveId(null);
    }
  });
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Flex, {
    overflow: "hidden",
    position: "relative"
  }, arrowLeft && /*#__PURE__*/React.createElement(Arrow, {
    onClick: scrollLeft,
    name: "navLeft"
  }), /*#__PURE__*/React.createElement(Container, {
    ref: mergeRefs(containerRef, ref)
  }, /*#__PURE__*/React.createElement(SortableContext, {
    items: items,
    strategy: strategy
  }, items.map(function (item, index) {
    return /*#__PURE__*/React.createElement(SortableItem, _extends({
      key: item.id + "-" + index,
      itemProps: item,
      id: item.id,
      draggable: !item.fixed,
      index: index,
      onRemove: onTabClose,
      animateLayoutChanges: animateLayoutChanges,
      Item: Item
    }, index === items.length - 1 && {
      lastTabRef: lastTabRef
    }, {
      collapsed: collapsed
    }));
  }))), arrowRight && /*#__PURE__*/React.createElement(Arrow, {
    onClick: scrollRight,
    name: "navRight",
    right: true
  })), /*#__PURE__*/createPortal(/*#__PURE__*/React.createElement(DragOverlay, {
    adjustScale: adjustScale,
    dropAnimation: dropAnimation
  }, activeId !== null ? /*#__PURE__*/React.createElement(Item, _extends({}, items[activeIndex], {
    backgroundOpacity: 0.8,
    isDragOverlay: true,
    grabbing: true,
    sorting: true
  })) : null), document.body));
};
var Sortable = function Sortable(_ref4) {
  var activationConstraint = _ref4.activationConstraint,
    _ref4$collisionDetect = _ref4.collisionDetection,
    collisionDetection = _ref4$collisionDetect === void 0 ? closestCenter : _ref4$collisionDetect,
    _ref4$measuring = _ref4.measuring,
    measuring = _ref4$measuring === void 0 ? {
      droppable: {
        strategy: MeasuringStrategy.Always
      }
    } : _ref4$measuring,
    modifiers = _ref4.modifiers,
    rest = _objectWithoutPropertiesLoose(_ref4, _excluded);
  var sensors = useSensors(useSensor(MouseSensor, {
    activationConstraint: activationConstraint
  }), useSensor(TouchSensor, {
    activationConstraint: activationConstraint
  }));
  return /*#__PURE__*/React.createElement(DndContext, {
    sensors: sensors,
    collisionDetection: collisionDetection,
    measuring: measuring,
    modifiers: modifiers
  }, /*#__PURE__*/React.createElement(BaseSortable, rest));
};
export default Sortable;