import { useEffect } from 'react';

var useDraggable = function useDraggable(_ref) {
  var _ref$active = _ref.active,
      active = _ref$active === void 0 ? false : _ref$active,
      dragTargetRef = _ref.dragTargetRef,
      dragHandleRef = _ref.dragHandleRef;
  useEffect(function () {
    var currentDragTargetRef = dragTargetRef === null || dragTargetRef === void 0 ? void 0 : dragTargetRef.current;
    var currentDragHandleRef = dragHandleRef === null || dragHandleRef === void 0 ? void 0 : dragHandleRef.current;

    if (!active || !currentDragTargetRef || !currentDragHandleRef) {
      return;
    }

    var x = 0;
    var y = 0;

    var mouseMoveHandler = function mouseMoveHandler(event) {
      var dx = event.clientX - x;
      var dy = event.clientY - y;
      currentDragTargetRef.style.top = "".concat(currentDragTargetRef.offsetTop + dy, "px");
      currentDragTargetRef.style.left = "".concat(currentDragTargetRef.offsetLeft + dx, "px");

      if (currentDragTargetRef.style.position !== 'absolute') {
        currentDragTargetRef.style.position = 'absolute';
      }

      x = event.clientX;
      y = event.clientY;
    };

    var mouseUpHandler = function mouseUpHandler() {
      document.removeEventListener('mousemove', mouseMoveHandler);
      document.removeEventListener('mouseup', mouseUpHandler);
    };

    var mouseDownHandler = function mouseDownHandler(event) {
      x = event.clientX;
      y = event.clientY;
      document.addEventListener('mousemove', mouseMoveHandler);
      document.addEventListener('mouseup', mouseUpHandler);
    };

    currentDragHandleRef.addEventListener('mousedown', mouseDownHandler);
    return function cleanup() {
      currentDragHandleRef.removeEventListener('mousedown', mouseDownHandler);
    };
  }, [active]);
};

export default useDraggable;