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

export default function FileUpload({ onUpload, onClose, maxSize = 25 }) {
  const [files, setFiles] = useState([]);
  const [isDragging, setIsDragging] = useState(false);
  const [comment, setComment] = useState('');
  const [isSpoiler, setIsSpoiler] = useState(false);
  const fileInputRef = useRef(null);

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

  const handleDragLeave = useCallback((e) => {
    e.preventDefault();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback((e) => {
    e.preventDefault();
    setIsDragging(false);
    
    const droppedFiles = Array.from(e.dataTransfer.files);
    addFiles(droppedFiles);
  }, []);

  const handleFileSelect = (e) => {
    const selectedFiles = Array.from(e.target.files);
    addFiles(selectedFiles);
  };

  const addFiles = (newFiles) => {
    const processedFiles = newFiles.map((file) => ({
      file,
      id: Date.now() + Math.random(),
      name: file.name,
      size: file.size,
      type: file.type,
      preview: file.type.startsWith('image/') ? URL.createObjectURL(file) : null,
      progress: 100, // Simulated upload progress
    }));
    
    setFiles((prev) => [...prev, ...processedFiles]);
  };

  const removeFile = (id) => {
    setFiles((prev) => {
      const removed = prev.find((f) => f.id === id);
      if (removed?.preview) {
        URL.revokeObjectURL(removed.preview);
      }
      return prev.filter((f) => f.id !== id);
    });
  };

  const formatSize = (bytes) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  const getFileIcon = (type) => {
    if (type.startsWith('image/')) return '🖼️';
    if (type.startsWith('video/')) return '🎬';
    if (type.startsWith('audio/')) return '🎵';
    if (type.includes('pdf')) return '📄';
    if (type.includes('zip') || type.includes('rar')) return '📦';
    if (type.includes('text') || type.includes('document')) return '📝';
    return '📎';
  };

  const handleUpload = () => {
    onUpload?.({
      files,
      comment,
      isSpoiler,
    });
    onClose?.();
  };

  const totalSize = files.reduce((acc, f) => acc + f.size, 0);
  const isOverLimit = totalSize > maxSize * 1024 * 1024;

  return (
    <div className="file-upload-modal">
      <div className="file-upload-header">
        <h3>Upload to #general</h3>
        <button className="upload-close" onClick={onClose}>✕</button>
      </div>

      <div 
        className={`file-drop-zone ${isDragging ? 'dragging' : ''}`}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={() => fileInputRef.current?.click()}
      >
        <input
          ref={fileInputRef}
          type="file"
          multiple
          onChange={handleFileSelect}
          style={{ display: 'none' }}
        />
        <div className="drop-zone-content">
          <span className="drop-icon">📁</span>
          <p>Drag & drop files here or click to browse</p>
          <span className="drop-hint">Max file size: {maxSize} MB</span>
        </div>
      </div>

      {files.length > 0 && (
        <div className="file-list">
          {files.map((file) => (
            <div key={file.id} className="file-item">
              {file.preview ? (
                <img src={file.preview} alt={file.name} className="file-preview" />
              ) : (
                <div className="file-icon">{getFileIcon(file.type)}</div>
              )}
              <div className="file-info">
                <div className="file-name">{file.name}</div>
                <div className="file-size">{formatSize(file.size)}</div>
              </div>
              <button 
                className="file-remove"
                onClick={() => removeFile(file.id)}
              >
                ✕
              </button>
            </div>
          ))}
        </div>
      )}

      <div className="upload-options">
        <label className="spoiler-option">
          <input 
            type="checkbox"
            checked={isSpoiler}
            onChange={(e) => setIsSpoiler(e.target.checked)}
          />
          <span>Mark as spoiler</span>
        </label>
      </div>

      <div className="upload-comment">
        <textarea
          placeholder="Add a comment (optional)"
          value={comment}
          onChange={(e) => setComment(e.target.value)}
          rows={2}
        />
      </div>

      {isOverLimit && (
        <div className="upload-warning">
          Total size exceeds {maxSize} MB limit. Some files may not upload.
        </div>
      )}

      <div className="upload-footer">
        <div className="upload-summary">
          {files.length} file{files.length !== 1 ? 's' : ''} • {formatSize(totalSize)}
        </div>
        <div className="upload-actions">
          <button className="upload-cancel" onClick={onClose}>Cancel</button>
          <button 
            className="upload-submit"
            disabled={files.length === 0}
            onClick={handleUpload}
          >
            Upload
          </button>
        </div>
      </div>
    </div>
  );
}
