import React, { useEffect, useRef, useState } from 'react';
import { ImagePlus } from 'lucide-react';
import { useAddComposerFiles } from '../../contexts/ComposerContext';

const hasFiles = (event: DragEvent) =>
  Array.from(event.dataTransfer?.types ?? []).includes('Files');

/**
 * App-wide drop target: dragging image files anywhere over the window shows an
 * overlay and attaches them to the composer on drop.
 */
const DropZoneOverlay: React.FC = () => {
  const addFiles = useAddComposerFiles();
  const [active, setActive] = useState(false);
  const dragDepth = useRef(0);

  useEffect(() => {
    const onDragEnter = (event: DragEvent) => {
      if (!hasFiles(event)) return;
      event.preventDefault();
      dragDepth.current += 1;
      setActive(true);
    };
    const onDragOver = (event: DragEvent) => {
      if (hasFiles(event)) event.preventDefault();
    };
    const onDragLeave = (event: DragEvent) => {
      if (!hasFiles(event)) return;
      dragDepth.current = Math.max(0, dragDepth.current - 1);
      if (dragDepth.current === 0) setActive(false);
    };
    const onDrop = (event: DragEvent) => {
      if (!hasFiles(event)) return;
      event.preventDefault();
      dragDepth.current = 0;
      setActive(false);
      if (event.dataTransfer?.files?.length) addFiles(event.dataTransfer.files);
    };

    window.addEventListener('dragenter', onDragEnter);
    window.addEventListener('dragover', onDragOver);
    window.addEventListener('dragleave', onDragLeave);
    window.addEventListener('drop', onDrop);
    return () => {
      window.removeEventListener('dragenter', onDragEnter);
      window.removeEventListener('dragover', onDragOver);
      window.removeEventListener('dragleave', onDragLeave);
      window.removeEventListener('drop', onDrop);
    };
  }, [addFiles]);

  if (!active) return null;

  return (
    <div className="pointer-events-none fixed inset-0 z-[100] flex items-center justify-center bg-app-bg/70 p-6 backdrop-blur-sm">
      <div className="flex flex-col items-center gap-3 rounded-2xl border-2 border-dashed border-brand bg-app-surface px-10 py-8 text-center shadow-card">
        <span className="flex h-12 w-12 items-center justify-center rounded-full bg-brand-subtle text-brand-text">
          <ImagePlus size={22} />
        </span>
        <p className="text-sm font-medium text-app-text">Drop images to attach</p>
      </div>
    </div>
  );
};

export default DropZoneOverlay;
