// src/hooks/useDragAndDrop.ts
import { useState, useCallback } from 'react';

interface UseDragAndDropOptions {
  /**
   * Callback function that is triggered when files are dropped onto the element.
   * @param files The FileList object from the drop event.
   */
  onFilesDropped: (files: FileList) => void;
  /**
   * A boolean to disable the drag-and-drop functionality.
   */
  disabled?: boolean;
}

/**
 * A reusable hook to manage drag-and-drop functionality for a UI element.
 *
 * @param options - Configuration for the hook, including the onDrop callback and disabled state.
 * @returns An object containing the `isDragging` state and props to be spread onto the dropzone element.
 */
export const useDragAndDrop = <T extends HTMLElement>({ onFilesDropped, disabled = false }: UseDragAndDropOptions) => {
  const [isDragging, setIsDragging] = useState(false);

  const handleDragEnter = useCallback((e: React.DragEvent<T>) => {
    e.preventDefault();
    e.stopPropagation();
    if (!disabled) {
      setIsDragging(true);
    }
  }, [disabled]);

  const handleDragLeave = useCallback((e: React.DragEvent<T>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent<T>) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
    if (!disabled && e.dataTransfer.files && e.dataTransfer.files.length > 0) {
      onFilesDropped(e.dataTransfer.files);
    }
  }, [disabled, onFilesDropped]);

  // onDragOver must also be handled to allow onDrop to fire.
  const handleDragOver = handleDragEnter;

  return {
    isDragging,
    dropzoneProps: {
      onDragEnter: handleDragEnter,
      onDragLeave: handleDragLeave,
      onDrop: handleDrop,
      onDragOver: handleDragOver,
    },
  };
};