import React, { useState, useEffect , useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import careersBanner from '../assets/careers-banner.jpg';
import careerImg from '../assets/career.jpg';

const Careers = () => {
  const navigate = useNavigate();
  const [jobs, setJobs] = useState([]);
  const [selectedIndex, setSelectedIndex] = useState(null);
  const [showContactForm, setShowContactForm] = useState(false);
  const [formData, setFormData] = useState({
    fullName: '',
    email: '',
    phone: '',
    resume: null,
  });
  const [loading, setLoading] = useState(false);
  const [jobsLoading, setJobsLoading] = useState(true);
  const [jobsError, setJobsError] = useState(null);
  const [searchFilters, setSearchFilters] = useState({
    position: '',
    skills: '',
    location: ''
  });
  const [filteredJobs, setFilteredJobs] = useState([]);
  const [activeOnly, setActiveOnly] = useState(true);
  const [showSuccessMessage, setShowSuccessMessage] = useState(false);
  const resumeInputRef = useRef(null);
    // useEffect(() => {
    //   const handleShortcut = (e) => {
    //     if (e.altKey && e.key.toLowerCase() === "n") {
    //       navigate("/Apply");
    //     }
    //   };
    //   document.addEventListener("keydown", handleShortcut);

    //   // Cleanup event listener on unmount
    //   return () => {
    //     document.removeEventListener("keydown", handleShortcut);
    //   };
    // }, [navigate]);

  // Fetch jobs from backend API
  useEffect(() => {
    const fetchJobs = async () => {
      try {
        setJobsLoading(true);
        const response = await fetch(`${process.env.REACT_APP_API_BASE_URL}/api/jobs`);
        
        if (!response.ok) {
          throw new Error(`Failed to fetch jobs: ${response.status}`);
        }
        
        const jobsData = await response.json();
        setJobs(jobsData);
        setJobsError(null);
      } catch (error) {
        console.error("Error fetching jobs:", error);
        setJobsError("Failed to load job openings. Please try again later.");
      } finally {
        setJobsLoading(false);
      }
    };

    fetchJobs();
  }, []);

  // Filter jobs based on search criteria
  useEffect(() => {
    const filtered = jobs.filter(job => {
      // Check position filter
      const positionMatch = searchFilters.position === '' || 
        job.positionName?.toLowerCase().includes(searchFilters.position.toLowerCase());
      
      // Check skills filter
      const skillsMatch = searchFilters.skills === '' || 
        (Array.isArray(job.skills) && 
        job.skills.some(skill => 
          skill.toLowerCase().includes(searchFilters.skills.toLowerCase())
        ));
      
      // Check location filter
      const locationMatch = searchFilters.location === '' || 
        job.location?.toLowerCase().includes(searchFilters.location.toLowerCase());
      
      // Check active status
      const isActive = !job.closingDate || new Date(job.closingDate) >= new Date();
      
      return positionMatch && skillsMatch && locationMatch && 
        (!activeOnly || (activeOnly && job.isActive && isActive));
    });
    
    setFilteredJobs(filtered);
  }, [jobs, searchFilters, activeOnly]);

  const getDaysAgo = (dateString) => {
    if (!dateString) return 'Recently';
    
    const postedDate = new Date(dateString);
    const currentDate = new Date();
    const timeDiff = currentDate - postedDate;
    const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
    
    if (daysDiff === 0) return 'Today';
    if (daysDiff === 1) return '1 day ago';
    if (daysDiff < 7) return `${daysDiff} days ago`;
    if (daysDiff < 30) {
      const weeks = Math.floor(daysDiff / 7);
      return weeks === 1 ? '1 week ago' : `${weeks} weeks ago`;
    }
    if (daysDiff < 365) {
      const months = Math.floor(daysDiff / 30);
      return months === 1 ? '1 month ago' : `${months} months ago`;
    }
    const years = Math.floor(daysDiff / 365);
    return years === 1 ? '1 year ago' : `${years} years ago`;
  };

  const handleToggle = (index) => {
    setSelectedIndex((prevIndex) => (prevIndex === index ? null : index));
  };

  // const handleContactClick = () => {
  //   setShowContactForm(!showContactForm);
  // };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleFileChange = (e) => {
    setFormData((prev) => ({
      ...prev,
      resume: e.target.files[0] || null,
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!formData.resume) {
      alert("Please upload your resume.");
      return;
    }

    setLoading(true);
    try {
      const data = new FormData();
      data.append("fullName", formData.fullName);
      data.append("email", formData.email);
      data.append("phone", formData.phone);
      data.append("resume", formData.resume);

      const response = await fetch(`${process.env.REACT_APP_API_BASE_URL}/api/careers/contact`, {
        method: "POST",
        body: data,
      });

      const result = await response.json();

      if (response.ok) {
        alert(result.message || "Thank you for contacting our HR team. We will get back to you soon!");
        setFormData({
          fullName: "",
          email: "",
          phone: "",
          resume: null,
        });
        setShowContactForm(false);
      } else {
        alert(result.error || "Failed to submit the form. Please try again.");
      }
    } catch (error) {
      console.error("Error submitting form:", error);
      alert("Server error. Please try again later.");
    }
    setLoading(false);
  };

  const benefits = [
    { title: "Competitive Compensation", icon: "💰", description: "Industry-leading salaries and performance bonuses" },
    { title: "Professional Growth", icon: "📈", description: "Continuous learning opportunities and career advancement paths" },
    { title: "Work-Life Balance", icon: "⚖️", description: "Flexible work arrangements and generous leave policies" },
    { title: "Health & Wellness", icon: "🏥", description: "Comprehensive health insurance and wellness programs" },
    { title: "Innovative Culture", icon: "💡", description: "Work with cutting-edge technologies and industry experts" },
    // { title: "Global Impact", icon: "🌍", description: "Opportunity to work on projects with international reach" },
  ];

  return (
    <div className="bg-white text-gray-900 min-h-screen">
      {/* Hero Banner */}
      <div
        className="relative w-full h-[60vh] bg-center bg-cover flex items-center justify-center"
        style={{ backgroundImage: `url(${careersBanner})` }}
      >
        <div className="absolute inset-0 bg-gradient-to-r from-blue-900/80 to-blue-700/80 z-0" />
        <div className="relative z-10 text-center px-4 text-white max-w-4xl">
          <h1 className="text-4xl md:text-5xl lg:text-6xl font-extrabold mb-4 drop-shadow-lg">
            Build Your Future With Us
          </h1>
          <p className="text-lg md:text-2xl font-medium drop-shadow mb-8">
            Shape India's infrastructure landscape while advancing your professional journey.
          </p>
          <button
            onClick={() => document.getElementById('openings').scrollIntoView({ behavior: 'smooth' })}
            className="bg-white text-blue-900 px-8 py-3 rounded-md font-bold hover:bg-gray-100 transition shadow-lg"
          >
            Explore Opportunities
          </button>
        </div>
      </div>

      {/* Why Join Us Section */}
      <div className="bg-gray-50 py-16">
        <div className="max-w-6xl mx-auto px-4">
          <h2 className="text-3xl font-bold text-blue-900 mb-2 text-center">
            Why Build Your Career With Us?
          </h2>
          <p className="text-gray-600 text-center max-w-3xl mx-auto mb-12">
            We're committed to fostering an environment where professionals can thrive, innovate,
            and make meaningful contributions to India's infrastructure development.
          </p>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {benefits.map((benefit, index) => (
              <div key={index} className="bg-white p-6 rounded-lg shadow-md hover:shadow-xl transition">
                <div className="text-4xl mb-4">{benefit.icon}</div>
                <h3 className="text-xl font-semibold text-blue-800 mb-2">{benefit.title}</h3>
                <p className="text-gray-600">{benefit.description}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Our Culture Section */}
      <div className="py-16 bg-white">
        <div className="max-w-6xl mx-auto px-4">
          <div className="flex flex-col lg:flex-row gap-12 items-center">
            <div className="lg:w-1/2">
              <h2 className="text-3xl font-bold text-blue-900 mb-6">Our Professional Culture</h2>
              <p className="text-gray-700 mb-4 leading-relaxed">
                At our company, we cultivate a culture of excellence, collaboration, and continuous
                improvement. We believe that our people are our greatest asset, and we invest in their
                professional development.
              </p>
              <p className="text-gray-700 mb-6 leading-relaxed">
                Our teams work on challenging projects that push the boundaries of infrastructure
                development, while maintaining the highest standards of professional ethics and quality.
              </p>
              <div className="flex flex-wrap gap-4">
                <span className="bg-blue-100 text-blue-800 px-4 py-2 rounded-full text-sm font-medium">Innovation</span>
                <span className="bg-blue-100 text-blue-800 px-4 py-2 rounded-full text-sm font-medium">Integrity</span>
                <span className="bg-blue-100 text-blue-800 px-4 py-2 rounded-full text-sm font-medium">Excellence</span>
                <span className="bg-blue-100 text-blue-800 px-4 py-2 rounded-full text-sm font-medium">Collaboration</span>
              </div>
            </div>
           <div className="lg:w-1/2 bg-gray-100 rounded-xl overflow-hidden">
            <img
              src={careerImg}
              alt="Company Culture"
              className="w-full h-80 object-cover"
            />
          </div>


          </div>
        </div>
      </div>

      {/* Current Openings Section */}
      <div id="openings" className="max-w-6xl mx-auto px-4 py-16">
        <div className="text-center mb-12">
          <h2 className="text-3xl font-bold text-blue-900 mb-2">
            Current Professional Opportunities
          </h2>
          <p className="text-gray-600 max-w-2xl mx-auto">
            Explore our current openings and find the perfect position to advance your professional career.
          </p>
        </div>

        {/* Loading state */}
        {jobsLoading && (
          <div className="text-center py-12">
            <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mb-4"></div>
            <p className="text-gray-600">Loading job openings...</p>
          </div>
        )}

        {/* Error state */}
        {jobsError && (
          <div className="text-center py-12 bg-red-50 rounded-lg">
            <p className="text-red-600 mb-4">{jobsError}</p>
            <button
              onClick={() => window.location.reload()}
              className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md font-medium"
            >
              Try Again
            </button>
          </div>
        )}

        {/* Jobs listing */}
        {!jobsLoading && !jobsError && (
          <>
            {/* Enhanced Search Filters */}
            <div className="mb-8 grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="relative">
                <input
                  type="text"
                  placeholder="Filter by position..."
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                  value={searchFilters.position}
                  onChange={(e) => setSearchFilters({...searchFilters, position: e.target.value})}
                />
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <svg className="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                </div>
              </div>
              
              <div className="relative">
                <input
                  type="text"
                  placeholder="Filter by skills..."
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                  value={searchFilters.skills}
                  onChange={(e) => setSearchFilters({...searchFilters, skills: e.target.value})}
                />
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <svg className="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                  </svg>
                </div>
              </div>
              
              <div className="relative">
                <input
                  type="text"
                  placeholder="Filter by location..."
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                  value={searchFilters.location}
                  onChange={(e) => setSearchFilters({...searchFilters, location: e.target.value})}
                />
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <svg className="h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                  </svg>
                </div>
              </div>
              
              <div className="md:col-span-3 flex justify-between items-center">
                <div className="flex items-center">
                  <input
                    type="checkbox"
                    id="activeOnly"
                    checked={activeOnly}
                    onChange={() => setActiveOnly(!activeOnly)}
                    className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                  />
                  <label htmlFor="activeOnly" className="ml-2 text-sm text-gray-700">
                    Show active positions only
                  </label>
                </div>
                
                {(searchFilters.position || searchFilters.skills || searchFilters.location) && (
                  <button
                    onClick={() => setSearchFilters({ position: '', skills: '', location: '' })}
                    className="text-blue-600 hover:text-blue-800 font-medium text-sm"
                  >
                    Clear all filters
                  </button>
                )}
              </div>
            </div>

            {filteredJobs.length > 0 ? (
              <div className="grid grid-cols-1 gap-6">
                {filteredJobs.map((job, index) => {
                  const closingDate = job.closingDate ? new Date(job.closingDate) : null;
                  const isExpired = closingDate ? new Date() > closingDate : false;
                  const actualStatus = isExpired ? false : job.isActive;

                  return (
                    <div
                      key={job.id}
                      className={`bg-white rounded-xl border border-gray-200 shadow-sm hover:shadow-md transition p-6 relative overflow-hidden ${!actualStatus ? 'opacity-80' : ''}`}
                    >
                      <div className={`absolute top-0 left-0 w-1 h-full ${actualStatus ? 'bg-blue-700' : 'bg-gray-400'}`}></div>

                      <div className="absolute -left-6 top-6 text-5xl text-blue-100 font-extrabold opacity-30 select-none">
                        {String(index + 1).padStart(2, '0')}
                      </div>

                      <div className="flex flex-col md:flex-row justify-between md:items-center mb-4 pl-4">
                        <div>
                          <h3 className="text-blue-900 font-bold text-xl md:text-2xl">
                            {job.positionName}
                          </h3>
                          <div className="flex flex-wrap gap-2 mt-2">
                            <span className="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-xs font-medium">
                              {job.location}
                            </span>
                            <span className="bg-green-100 text-green-800 px-3 py-1 rounded-full text-xs font-medium">
                              {job.experience}
                            </span>
                            <span className="bg-purple-100 text-purple-800 px-3 py-1 rounded-full text-xs font-medium">
                              {getDaysAgo(job.postingDate)}
                            </span>
                            {!actualStatus && (
                              <span className="bg-red-100 text-red-800 px-3 py-1 rounded-full text-xs font-medium">
                                Position Closed
                              </span>
                            )}
                          </div>
                        </div>
                        <div className="flex gap-2 mt-4 md:mt-0">
                          <button
                            onClick={() => handleToggle(index)}
                            className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md font-medium shadow transition flex items-center gap-2 text-sm"
                          >
                            {selectedIndex === index ? (
                              <>
                                <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
                                </svg>
                                Hide
                              </>
                            ) : (
                              <>
                                <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                                </svg>
                                Details
                              </>
                            )}
                          </button>
                          {actualStatus && (
                            <button
                              onClick={() => navigate('/job-application', { state: { jobId: job.id } })}
                              className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-md font-medium shadow transition flex items-center gap-2 text-sm"
                            >
                              <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                              </svg>
                              Apply
                            </button>
                          )}
                        </div>
                      </div>

                      {selectedIndex === index && (
                        <div className="bg-gray-50 p-5 rounded-md border border-blue-100 mt-4 ml-4">
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                              <h4 className="font-semibold text-blue-800 mb-3">Position Overview</h4>
                              <div className="space-y-4 text-sm text-gray-700">
                                <div>
                                  <p className="font-medium text-gray-500">Qualification</p>
                                  <p>{job.qualification || 'Not specified'}</p>
                                </div>
                                <div>
                                  <p className="font-medium text-gray-500">Experience</p>
                                  <p>{job.experience || 'Not specified'}</p>
                                </div>
                                <div>
                                  <p className="font-medium text-gray-500">Location</p>
                                  <p>{job.location || 'Not specified'}</p>
                                </div>
                                <div>
                                  <p className="font-medium text-gray-500">Posted</p>
                                  <p>{getDaysAgo(job.postingDate)}</p>
                                </div>
                                {job.closingDate && (
                                  <div>
                                    <p className="font-medium text-gray-500">Closing Date</p>
                                    <p>{new Date(job.closingDate).toLocaleDateString()}</p>
                                  </div>
                                )}
                              </div>
                            </div>
                            <div>
                              <h4 className="font-semibold text-blue-800 mb-3">Position Details</h4>
                              <div className="space-y-4 text-sm text-gray-700">
                                
                                <div>
                                  <p className="font-medium text-gray-500">Openings</p>
                                  <p>{job.numberOfOpenings || '1'}</p>
                                </div>
                                <div>
                                  <p className="font-medium text-gray-500">Key Skills</p>
                                  <div className="flex flex-wrap gap-1 mt-1">
                                    {Array.isArray(job.skills) && job.skills.length > 0 ? (
                                      job.skills.map((skill, i) => (
                                        <span
                                          key={i}
                                          className="inline-flex px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
                                        >
                                          {skill}
                                        </span>
                                      ))
                                    ) : (
                                      <span className="text-sm text-gray-500">Not specified</span>
                                    )}
                                  </div>
                                </div>
                              </div>
                            </div>
                            <div className="md:col-span-2">
                              <h4 className="font-semibold text-blue-800 mb-3">Job Description</h4>
                              <div className="prose prose-sm max-w-none text-gray-700">
                                <p>{job.jobDescription || 'No description provided.'}</p>
                              </div>
                            </div>
                          </div>

                          {actualStatus && (
                            <div className="flex justify-end mt-6">
                              <button
                                onClick={() => navigate('/job-application', { state: { jobId: job.id } })}
                                className="bg-green-600 hover:bg-green-700 text-white px-8 py-3 rounded-md font-medium shadow-md transition flex items-center gap-2"
                              >
                                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                                </svg>
                                Apply for this Position
                              </button>
                            </div>
                          )}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            ) : (
              !jobsLoading && (
                <div className="text-center py-12 bg-gray-50 rounded-lg">
                  <p className="text-gray-600">
                    {jobs.length === 0 
                      ? "No positions are currently available. Please check back later." 
                      : "No positions match your current filters."}
                  </p>
                  {(searchFilters.position || searchFilters.skills || searchFilters.location) && (
                    <button
                      onClick={() => {
                        setSearchFilters({ position: '', skills: '', location: '' });
                        setActiveOnly(true);
                      }}
                      className="mt-4 text-blue-600 hover:text-blue-800 font-medium"
                    >
                      Clear all filters
                    </button>
                  )}
                </div>
              )
            )}
          </>
        )}
      </div>

      {/* Call to Action - Contact HR Section (Kept exactly as before) */}
      <div className="bg-blue-900 text-white py-16">
        <div className="max-w-4xl mx-auto px-4 text-center">
          <h2 className="text-3xl font-bold mb-4">Ready to Build Your Professional Future?</h2>
          <p className="text-blue-100 mb-8 text-lg">
            Even if you don't see the perfect role today, we're always interested in connecting with talented professionals.
          </p>
          {/* <div className="flex flex-col sm:flex-row justify-center gap-4">
            <button
              onClick={handleContactClick}
              className="bg-white text-blue-900 px-8 py-3 rounded-md font-bold hover:bg-gray-100 transition shadow-lg"
            >
              Stay connected with us
            </button>
          </div> */}

          
            <div className="mt-8 bg-white rounded-lg shadow-xl p-6 max-w-2xl mx-auto text-left text-gray-800 relative">
            {/* Success Popup */}
            {showSuccessMessage && (
              <div className="absolute inset-0 bg-black/30 flex items-center justify-center z-50">
                <div className="bg-green-100 text-green-800 px-6 py-4 rounded-md shadow-md text-center max-w-sm">
                  <p className="font-semibold text-lg">Thank you for connecting!</p>
                  <p className="text-sm mt-1">We will get back to you soon.</p>
                  <button
                    onClick={() => setShowSuccessMessage(false)}
                    className="mt-3 px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition"
                  >
                    OK
                  </button>
                </div>
              </div>
            )}

            <h3 className="text-2xl font-bold text-blue-900 mb-4">Let’s Connect With Us</h3>
            <form
              onSubmit={async (e) => {
                e.preventDefault();

                if (!formData.resume) {
                  alert("Please upload your resume.");
                  return;
                }

                setLoading(true);
                try {
                  const data = new FormData();
                  data.append("fullName", formData.fullName);
                  data.append("email", formData.email);
                  data.append("phone", formData.phone);
                  data.append("resume", formData.resume);

                  const response = await fetch(`${process.env.REACT_APP_API_BASE_URL}/api/careers/contact`, {
                    method: "POST",
                    body: data,
                  });

                  const result = await response.json();

                  if (response.ok) {
                    // Show popup message
                    setShowSuccessMessage(true);

                    // Reset the form
                    setFormData({
                      fullName: "",
                      email: "",
                      phone: "",
                      resume: null,
                    });
                    if (resumeInputRef.current) {
                      resumeInputRef.current.value = null;
                    }
                    } else {
                    alert(result.error || "Failed to submit the form. Please try again.");
                  }
                } catch (error) {
                  console.error("Error submitting form:", error);
                  alert("Server error. Please try again later.");
                }
                setLoading(false);
              }}
            >
              {/* Full Name */}
              <div className="mb-4">
                <label htmlFor="fullName" className="block text-gray-700 font-medium mb-2">
                  Full Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  id="fullName"
                  name="fullName"
                  value={formData.fullName}
                  onChange={handleInputChange}
                  className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
                />
              </div>

              {/* Email */}
              <div className="mb-4">
                <label htmlFor="email" className="block text-gray-700 font-medium mb-2">
                  Email <span className="text-red-500">*</span>
                </label>
                <input
                  type="email"
                  id="email"
                  name="email"
                  value={formData.email}
                  onChange={handleInputChange}
                  className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  required
                />
              </div>

              {/* Phone */}
              <div className="mb-4">
                <label htmlFor="phone" className="block text-gray-700 font-medium mb-2">
                  Phone Number
                </label>
                <input
                  type="tel"
                  id="phone"
                  name="phone"
                  value={formData.phone}
                  onChange={handleInputChange}
                  className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* Resume */}
              <div className="mb-6">
                <label htmlFor="resume" className="block text-gray-700 font-medium mb-2">
                  Upload Resume (PDF) <span className="text-red-500">*</span>
                </label>
                <input
                  type="file"
                  id="resume"
                  name="resume"
                  ref={resumeInputRef}   // <-- add this
                  onChange={handleFileChange}
                  className="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  accept=".pdf,.doc,.docx"
                  required
                />
              </div>

              <div className="flex justify-end gap-4">
                <button
                  type="submit"
                  className={`px-6 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition flex items-center justify-center gap-2 ${loading ? 'opacity-50 cursor-not-allowed' : ''}`}
                  disabled={loading}
                >
                  {loading && (
                    <svg
                      className="animate-spin h-5 w-5 text-white"
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      ></circle>
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8v8H4z"
                      ></path>
                    </svg>
                  )}
                  Submit
                </button>
              </div>
            </form>
          </div>

        </div>
      </div>
    </div>
  );
};

export default Careers;