import { useCallback, useEffect, useRef, useState } from 'react';
import { globalObject } from '@skbkontur/global-object';
export var useDrop = function useDrop(props) {
  if (props === void 0) {
    props = {};
  }
  var _props = props,
    onDrop = _props.onDrop;
  var droppableRef = useRef(null);
  var overRef = useRef(false);
  var timerId = useRef();
  var _useState = useState(false),
    isDraggable = _useState[0],
    setIsDraggable = _useState[1];
  var clearTimer = useCallback(function () {
    timerId.current && globalObject.clearTimeout(timerId.current);
  }, []);
  var handleDragOver = useCallback(function (event) {
    event.preventDefault();
    setIsDraggable(true);
    clearTimer();
    timerId.current = globalObject.setTimeout(function () {
      overRef.current = false;
      setIsDraggable(false);
    }, 200);
  }, [clearTimer]);
  var preventDefault = useCallback(function (event) {
    event.preventDefault();
    event.stopPropagation();
  }, []);
  var handleDrop = useCallback(function (event) {
    preventDefault(event);
    setIsDraggable(false);
    overRef.current = false;
    onDrop == null || onDrop(event);
  }, [preventDefault, onDrop]);
  useEffect(function () {
    var ref = droppableRef.current;
    if (!ref) {
      return;
    }
    ref.addEventListener('dragenter', preventDefault);
    ref.addEventListener('dragleave', preventDefault);
    ref.addEventListener('dragover', handleDragOver);
    ref.addEventListener('drop', handleDrop);
    return function () {
      ref.removeEventListener('dragenter', preventDefault);
      ref.removeEventListener('dragleave', preventDefault);
      ref.removeEventListener('dragover', handleDragOver);
      ref.removeEventListener('drop', handleDrop);
    };
  }, [handleDrop, handleDragOver, preventDefault]);
  return {
    isDraggable: isDraggable,
    ref: droppableRef
  };
};