import { useState, useEffect } from 'react';

/**
 * Custom hook for handling element dragging with grid snapping
 * @param {Object} params
 * @param {boolean} params.isSelected - Whether element is selected
 * @param {Function} params.onDragStart - Callback when drag starts
 * @param {Function} params.onDrag - Callback during drag
 * @param {string} params.toolMode - Current tool mode
 * @returns {Object} Drag state and handlers
 */
export function useElementDrag({ isSelected, onDragStart, onDrag, toolMode }) {
  const [isDragging, setIsDragging] = useState(false);
  const [dragData, setDragData] = useState(null);

  const handleMouseDown = (e, elementId) => {
    // Only handle dragging in select mode
    if (toolMode !== 'select') return;

    e.stopPropagation();

    setIsDragging(true);
    const data = onDragStart(elementId, e.clientX, e.clientY);
    setDragData({ ...data, startMouseX: e.clientX, startMouseY: e.clientY });
  };

  useEffect(() => {
    if (!isDragging) return;

    // Add class to body to disable transitions globally during drag
    document.body.classList.add('dragging-active');

    const handleMouseMove = (e) => {
      if (dragData) {
        const deltaX = e.clientX - dragData.startMouseX;
        const deltaY = e.clientY - dragData.startMouseY;
        onDrag(dragData, deltaX, deltaY);
      }
    };

    const handleMouseUp = () => {
      setIsDragging(false);
      setDragData(null);
      document.body.classList.remove('dragging-active');
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
      document.body.classList.remove('dragging-active');
    };
  }, [isDragging, dragData, onDrag]);

  return {
    isDragging,
    handleMouseDown
  };
}
