import React, { useRef, useState } from 'react';

interface FileUploadProps {
  accept?: string;
  multiple?: boolean;
  onChange: (files: File[]) => void;
  maxFiles?: number;
  maxSize?: number;
  children?: React.ReactNode;
  className?: string;
}

export const FileUpload: React.FC<FileUploadProps> = ({
  accept,
  multiple = false,
  onChange,
  maxFiles = 1,
  maxSize,
  children,
  className = ''
}) => {
  const [dragActive, setDragActive] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);

  const handleFiles = (files: FileList | null) => {
    if (!files) return;

    let filesArray = Array.from(files);
    
    // Apply max files constraint
    if (multiple && filesArray.length > maxFiles) {
      filesArray = filesArray.slice(0, maxFiles);
    } else if (!multiple && filesArray.length > 1) {
      filesArray = filesArray.slice(0, 1);
    }

    // Apply max size constraint
    if (maxSize) {
      filesArray = filesArray.filter(file => file.size <= maxSize);
    }

    setSelectedFiles(prev => multiple ? [...prev, ...filesArray] : filesArray);
    onChange(multiple ? [...selectedFiles, ...filesArray] : filesArray);
  };

  const handleDrag = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === 'dragenter' || e.type === 'dragover') {
      setDragActive(true);
    } else if (e.type === 'dragleave') {
      setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setDragActive(false);
    handleFiles(e.dataTransfer.files);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    handleFiles(e.target.files);
  };

  const onButtonClick = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };

  const removeFile = (index: number) => {
    const newFiles = selectedFiles.filter((_, i) => i !== index);
    setSelectedFiles(newFiles);
    onChange(newFiles);
  };

  return (
    <div className={`relative ${className}`}>
      <form 
        className={`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer transition-colors ${
          dragActive 
            ? 'border-blue-500 bg-blue-50' 
            : 'border-gray-300 hover:border-gray-400'
        }`}
        onDragEnter={handleDrag}
        onDragOver={handleDrag}
        onDragLeave={handleDrag}
        onDrop={handleDrop}
        onClick={onButtonClick}
      >
        <input
          ref={fileInputRef}
          type="file"
          multiple={multiple}
          accept={accept}
          onChange={handleChange}
          className="hidden"
        />
        
        {children || (
          <div>
            <p className="text-gray-600 mb-2">
              Drag & drop files here, or click to select
            </p>
            <p className="text-sm text-gray-500">
              {accept ? `Accepted: ${accept}` : 'Any file type accepted'}
              {maxSize && `, Max size: ${(maxSize / (1024 * 1024)).toFixed(1)}MB`}
            </p>
          </div>
        )}
      </form>

      {/* Preview selected files */}
      {selectedFiles.length > 0 && (
        <div className="mt-4 space-y-2">
          <h4 className="text-sm font-medium text-gray-700">Selected Files:</h4>
          <ul className="space-y-1">
            {selectedFiles.map((file, index) => (
              <li key={index} className="flex justify-between items-center bg-gray-50 p-2 rounded text-sm">
                <span className="truncate max-w-xs">{file.name}</span>
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation();
                    removeFile(index);
                  }}
                  className="ml-2 text-red-500 hover:text-red-700"
                >
                  ×
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
};

export default FileUpload;