/**
 * ImageDropZone.jsx - Drag & drop overlay voor afbeeldingen
 *
 * Toont een overlay wanneer bestanden over de editor gesleept worden.
 * Bij drop: valideert het bestandstype, upload naar de server,
 * en voegt de Markdown afbeelding-syntax in op de cursorpositie.
 */

import { useState, useCallback } from 'react';

/**
 * @param {object} props
 * @param {React.ReactNode} props.children - De editor content
 * @param {React.RefObject} props.textareaRef - Ref naar de textarea
 * @param {function} props.onChange - Callback wanneer content wijzigt (na afbeelding invoegen)
 */
export default function ImageDropZone({ children, textareaRef, onChange, className = '' }) {
  const [isDragging, setIsDragging] = useState(false);
  const [uploadStatus, setUploadStatus] = useState(null);

  const handleDragEnter = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
    // Alleen sluiten als we het drop zone element echt verlaten
    if (e.currentTarget.contains(e.relatedTarget)) return;
    setIsDragging(false);
  }, []);

  const handleDragOver = useCallback((e) => {
    e.preventDefault();
    e.stopPropagation();
  }, []);

  const handleDrop = useCallback(async (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);

    const files = Array.from(e.dataTransfer.files);
    const imageFile = files.find(f => f.type.startsWith('image/'));

    if (!imageFile) {
      setUploadStatus({ type: 'error', message: 'Alleen afbeeldingen worden geaccepteerd' });
      setTimeout(() => setUploadStatus(null), 3000);
      return;
    }

    // Valideer bestandstype
    const allowed = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
    if (!allowed.includes(imageFile.type)) {
      setUploadStatus({ type: 'error', message: `Type ${imageFile.type} niet ondersteund` });
      setTimeout(() => setUploadStatus(null), 3000);
      return;
    }

    setUploadStatus({ type: 'uploading', message: 'Uploaden...' });

    try {
      const formData = new FormData();
      formData.append('file', imageFile);

      const response = await fetch('/__editor/upload', {
        method: 'POST',
        body: formData,
      });

      const result = await response.json();

      if (!response.ok) {
        throw new Error(result.error || 'Upload mislukt');
      }

      // Voeg Markdown afbeelding in op de cursorpositie
      const textarea = textareaRef.current;
      if (textarea) {
        const start = textarea.selectionStart;
        const value = textarea.value;
        const imgMarkdown = `![${result.filename}](${result.path})`;

        // Voeg lege regels toe als de cursor midden in tekst staat
        const before = start > 0 && value[start - 1] !== '\n' ? '\n\n' : '';
        const after = start < value.length && value[start] !== '\n' ? '\n\n' : '';
        const insertion = `${before}${imgMarkdown}${after}`;

        const newValue = value.substring(0, start) + insertion + value.substring(start);
        textarea.value = newValue;
        textarea.selectionStart = start + insertion.length;
        textarea.selectionEnd = start + insertion.length;
        textarea.focus();
        onChange(newValue);
      }

      setUploadStatus({ type: 'success', message: `${result.filename} toegevoegd` });
      setTimeout(() => setUploadStatus(null), 3000);
    } catch (err) {
      setUploadStatus({ type: 'error', message: err.message });
      setTimeout(() => setUploadStatus(null), 5000);
    }
  }, [textareaRef, onChange]);

  return (
    <div
      className={`relative ${className}`}
      onDragEnter={handleDragEnter}
      onDragLeave={handleDragLeave}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
    >
      {children}

      {/* Drag overlay */}
      {isDragging && (
        <div className="absolute inset-0 bg-coral-500/10 border-2 border-dashed border-coral-400 rounded-lg flex items-center justify-center z-10 pointer-events-none">
          <div className="bg-white rounded-xl px-6 py-4 shadow-lg text-center">
            <svg className="w-10 h-10 text-coral-500 mx-auto mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
            <p className="font-semibold text-warm-800">Afbeelding hier loslaten</p>
            <p className="text-sm text-warm-500">PNG, JPG, GIF of WebP</p>
          </div>
        </div>
      )}

      {/* Upload status melding */}
      {uploadStatus && (
        <div className={`absolute bottom-4 left-1/2 -translate-x-1/2 px-4 py-2 rounded-lg text-sm font-medium shadow-lg z-20 ${
          uploadStatus.type === 'error' ? 'bg-red-100 text-red-700' :
          uploadStatus.type === 'success' ? 'bg-teal-100 text-teal-700' :
          'bg-warm-100 text-warm-600'
        }`}>
          {uploadStatus.message}
        </div>
      )}
    </div>
  );
}
