import React, { useState } from "react";
import { FaTimes, FaUpload, FaFileAlt } from "react-icons/fa";
import { useTheme } from "../../contexts/ThemeContext";

const AddFormModal = ({ isOpen, onClose, onSubmit }) => {
  const [projectType, setProjectType] = useState("");
  const [selectedFile, setSelectedFile] = useState(null);
  const [fileBlob, setFileBlob] = useState(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { isLight } = useTheme();

  const modalBgClass = isLight ? "bg-white" : "bg-slate-800";

  const inputClass = isLight
    ? "bg-white text-gray-900 border-yellow-200 focus:ring-amber-500 focus:border-amber-500"
    : "bg-slate-700 text-slate-100 border-slate-600 focus:ring-cyan-400 focus:border-cyan-400 hover:border-slate-500";

  const buttonClass = isLight
    ? "bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-600 hover:to-amber-600 text-white"
    : "bg-blue-600 hover:bg-blue-700 text-white shadow-lg";

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      // Check file type (only allow .docx, .doc - Word documents only)
      const allowedTypes = [
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/msword'
      ];
      
             if (allowedTypes.includes(file.type)) {
         setSelectedFile(file);
         
         // Convert file to blob
         const blob = new Blob([file], { type: file.type });
         setFileBlob(blob);
       } else {
         // Invalid file type - reset form silently
         e.target.value = '';
         setSelectedFile(null);
         setFileBlob(null);
       }
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
         if (!projectType.trim() || !selectedFile || !fileBlob) {
       // Form validation failed - return silently
       return;
     }

    setIsSubmitting(true);
    
    try {
      // Create form data with blob
      const formData = new FormData();
      formData.append('project_type', projectType.trim());
      formData.append('document', fileBlob, selectedFile.name);

      await onSubmit(formData);
      
      // Reset form
      setProjectType("");
      setSelectedFile(null);
      setFileBlob(null);
      onClose();
         } catch (error) {
       // Silent failure - no alert shown
     } finally {
      setIsSubmitting(false);
    }
  };

  const handleClose = () => {
    if (!isSubmitting) {
      setProjectType("");
      setSelectedFile(null);
      setFileBlob(null);
      onClose();
    }
  };



  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 flex items-center justify-center z-50 p-4"
      style={{ backgroundColor: "rgba(0, 0, 0, 0.1)" }}
    >
      <div
        className={`${modalBgClass} rounded-lg max-w-md w-full border ${
          isLight ? "border-yellow-200" : "border-slate-600 shadow-2xl"
        }`}
      >
        {/* Header */}
        <div className={`flex items-center justify-between p-6 border-b ${
          isLight ? "border-yellow-200" : "border-slate-600"
        }`}>
          <h2 className={`text-xl font-semibold ${
            isLight ? "text-amber-800" : "text-slate-100"
          }`}>
            Add New Form
          </h2>
          <button
            onClick={handleClose}
            disabled={isSubmitting}
            className="text-gray-400 hover:text-gray-600 transition-colors duration-200 flex items-center justify-center w-8 h-8"
          >
            <FaTimes className="w-5 h-5 flex-shrink-0" />
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* Project Type */}
          <div>
            <label className={`block text-sm font-medium mb-2 ${
              isLight ? "text-amber-700" : "text-slate-300"
            }`}>
              Project Type *
            </label>
            <input
              type="text"
              value={projectType}
              onChange={(e) => setProjectType(e.target.value)}
              placeholder="e.g., E-commerce Platform, Mobile App"
              className={`w-full px-3 py-2 border rounded-lg focus:outline-none ${inputClass}`}
              disabled={isSubmitting}
              required
            />
          </div>

          {/* File Upload */}
          <div>
            <label className={`block text-sm font-medium mb-2 ${
              isLight ? "text-amber-700" : "text-slate-300"
            }`}>
              Form File *
            </label>
            <div className={`mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-dashed rounded-lg transition-colors duration-200 ${
              isLight ? "border-yellow-200 hover:border-amber-400" : "border-slate-600 hover:border-cyan-400"
            }`}>
              <div className="space-y-1 text-center">
                {selectedFile ? (
                  <div className="space-y-2">
                    <div className="flex items-center justify-center space-x-2 text-amber-600">
                      <FaFileAlt className="w-8 h-8" />
                      <span className="text-sm font-medium">{selectedFile.name}</span>
                    </div>

                  </div>
                ) : (
                  <>
                    <FaUpload className={`mx-auto h-12 w-12 ${
                      isLight ? "text-gray-400" : "text-slate-500"
                    }`} />
                    <div className={`flex text-sm ${
                      isLight ? "text-gray-600" : "text-slate-400"
                    }`}>
                      <label className="relative cursor-pointer rounded-md font-medium text-amber-600 hover:text-amber-500">
                        <span>Upload a file</span>
                        <input
                          type="file"
                          className="sr-only"
                          onChange={handleFileChange}
                          accept=".docx,.doc"
                          disabled={isSubmitting}
                        />
                      </label>
                      <p className="pl-1">or drag and drop</p>
                    </div>
                    <p className={`text-xs ${
                      isLight ? "text-gray-500" : "text-slate-500"
                    }`}>
                      DOCX, DOC up to 10MB
                    </p>
                  </>
                )}
              </div>
            </div>
          </div>

          {/* Buttons */}
          <div className="flex space-x-3 pt-4">
            <button
              type="button"
              onClick={handleClose}
              disabled={isSubmitting}
              className={`flex-1 px-4 py-2 border rounded-lg transition-colors duration-200 disabled:opacity-50 ${
                isLight 
                  ? "border-yellow-200 text-amber-700 hover:bg-yellow-50" 
                  : "border-slate-600 text-slate-300 hover:bg-slate-700"
              }`}
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={isSubmitting || !projectType.trim() || !selectedFile || !fileBlob}
              className={`flex-1 px-4 py-2 rounded-lg transition-all duration-200 hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed ${buttonClass}`}
            >
              {isSubmitting ? 'Uploading...' : 'Upload Form'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default AddFormModal;
