import { useEffect, useRef, useState } from 'react';
import throttle from 'lodash/throttle';
import { TOGGLE_BUTTON_PLACEMENTS } from './collapsible-sidebar';
export function useResize({
  panelElement,
  onWidthChange,
  sideBarPlacement,
  isResizeEnabled,
  isMinimized
}) {
  const [isResizing, setIsResizing] = useState(false);
  const moveHandlerRef = useRef(new AbortController());
  const upHandlerRef = useRef(new AbortController());
  const shouldToggleOnClick = useRef(true);
  const onMouseMoveHandler = event => {
    event.preventDefault();
    event.stopPropagation();
    shouldToggleOnClick.current = false;
    const sidePanelBoundingRect = panelElement.current.getBoundingClientRect();
    const delta = sideBarPlacement === TOGGLE_BUTTON_PLACEMENTS.right ? Math.round(event.clientX - sidePanelBoundingRect.right) : Math.round(sidePanelBoundingRect.left - event.clientX);
    const newWidth = sidePanelBoundingRect.width + delta;
    onWidthChange?.(newWidth);
  };
  const throttledMoveHandler = useRef(throttle(onMouseMoveHandler, 20)).current;
  const onMouseUpHandler = () => {
    if (isResizeEnabled) {
      moveHandlerRef?.current?.abort();
      setIsResizing(false);
    }
  };

  // subscribe to moseup handler which will cancel move listener
  useEffect(() => {
    document.addEventListener('mouseup', onMouseUpHandler, {
      signal: upHandlerRef.current.signal
    });
    return () => {
      moveHandlerRef?.current?.abort();
      upHandlerRef.current.abort();
    };
  }, []);
  const onMouseDownHandler = () => {
    // we add mousemove listener to the whole document only on mousedown on border.
    // we unsubscribe in the mouseup handler.
    // this is neede so that user can drag mouse anywhere on the screen as long as the mouse is clicked and sidebar panl would respond respectively
    if (isResizeEnabled && !isMinimized) {
      shouldToggleOnClick.current = true;
      moveHandlerRef.current = new AbortController();
      document.addEventListener('mousemove', throttledMoveHandler, {
        signal: moveHandlerRef.current.signal
      });
      setIsResizing(true);
    }
  };
  return {
    isResizing,
    shouldRespondToBorderClick: shouldToggleOnClick.current,
    onMouseDownHandler
  };
}