import { useRef, useState, type DragEvent } from 'react';
import { Icon } from './Icon';

export interface FileDropZoneProps {
  onFiles: (files: File[]) => void;
  compact?: boolean;
  disabled?: boolean;
}

export function FileDropZone({
  onFiles,
  compact = false,
  disabled = false,
}: FileDropZoneProps) {
  const input = useRef<HTMLInputElement>(null);
  const [dragging, setDragging] = useState(false);

  const receive = (files: FileList | null) => {
    const selected = files ? [...files].filter((file) => file.size > 0) : [];
    if (selected.length > 0) onFiles(selected);
    if (input.current) input.current.value = '';
  };

  const drop = (event: DragEvent<HTMLDivElement>) => {
    event.preventDefault();
    setDragging(false);
    if (!disabled) receive(event.dataTransfer.files);
  };

  return (
    <div
      className={[
        'drop-zone',
        compact ? 'drop-zone--compact' : '',
        dragging ? 'drop-zone--active' : '',
      ]
        .filter(Boolean)
        .join(' ')}
      onDragEnter={(event) => {
        event.preventDefault();
        if (!disabled) setDragging(true);
      }}
      onDragOver={(event) => event.preventDefault()}
      onDragLeave={(event) => {
        if (!event.currentTarget.contains(event.relatedTarget as Node | null)) {
          setDragging(false);
        }
      }}
      onDrop={drop}
    >
      <input
        ref={input}
        className="visually-hidden"
        type="file"
        accept="audio/*,video/*,.mkv,.mka,.flac,.wav,.ogg,.opus"
        multiple
        disabled={disabled}
        onChange={(event) => receive(event.currentTarget.files)}
      />
      <div className="drop-zone__icon">
        <Icon name="add" />
      </div>
      <div>
        <strong>{compact ? 'Add media' : 'Drop audio or video here'}</strong>
        <span>
          {compact
            ? 'Files stay on this device'
            : 'Any FFmpeg-supported local file · nothing is uploaded'}
        </span>
      </div>
      <button
        className="button button--secondary"
        type="button"
        disabled={disabled}
        onClick={() => input.current?.click()}
      >
        Choose files
      </button>
    </div>
  );
}
