import React, { useCallback } from 'react';
import { useDropzone } from 'react-dropzone';
import { motion } from 'framer-motion';
import axios from 'axios';
import { FaTimes } from 'react-icons/fa';

const UploadModal = ({ close, refresh }) => {
  const onDrop = useCallback(async (acceptedFiles) => {
    const formData = new FormData();
    
    // Separate HTML and Images
    acceptedFiles.forEach(file => {
      if (file.name.endsWith('.html')) {
        formData.append('htmlFile', file);
      } else if (file.name.endsWith('.png')) {
        formData.append('images', file);
      }
    });

    try {
      await axios.post('http://localhost:5000/api/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' }
      });
      refresh();
      close();
    } catch (err) {
      alert("Error uploading files");
    }
  }, [close, refresh]);

  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  return (
    <div className="fixed inset-0 bg-blue-900/20 backdrop-blur-sm flex items-center justify-center z-50">
      <motion.div 
        initial={{ opacity: 0, scale: 0.9 }}
        animate={{ opacity: 1, scale: 1 }}
        exit={{ opacity: 0, scale: 0.9 }}
        className="bg-black border border-gray-700 w-[600px] h-[400px] rounded-2xl p-4 flex flex-col relative"
      >
        <button onClick={close} className="absolute top-4 left-4 text-white hover:bg-gray-800 p-2 rounded-full">
          <FaTimes />
        </button>
        
        <div className="flex-1 flex flex-col items-center justify-center mt-8">
           <div {...getRootProps()} className={`border-2 border-dashed border-gray-600 rounded-xl w-full h-64 flex items-center justify-center cursor-pointer transition ${isDragActive ? 'bg-gray-900 border-blue-500' : ''}`}>
             <input {...getInputProps()} />
             <div className="text-center">
               <p className="text-blue-400 font-bold text-lg">Drop MT5 HTML & Images here</p>
               <p className="text-gray-500 text-sm">ReportTester-ID.html + 4 pngs</p>
             </div>
           </div>
        </div>
      </motion.div>
    </div>
  );
};

export default UploadModal;