'use client';

import { useEffect, useState } from "react";
import Container from "../atoms/Container";
import Heading from "../atoms/Heading";
import { JobOpportunitiesfirst } from "../molecules/Job-Opportunitiesfirst";
import Swal from "sweetalert2";
import { Search, Briefcase, MapPin, Clock, Filter } from 'lucide-react';

function JobOpportunitiesorgan() {
  const [jobs, setJobs] = useState([]);
  const [filteredJobs, setFilteredJobs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [activeFilter, setActiveFilter] = useState('all');
  const [locationFilter, setLocationFilter] = useState('');

  useEffect(() => {
    const fetchJobs = async () => {
      try {
        const response = await fetch("/api/frontend/jobs", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
        });
        if (!response.ok) {
          throw new Error("Failed to fetch jobs");
        }

        const data = await response.json();
        setJobs(data.data);
        setFilteredJobs(data.data);
        setLoading(false);

      } catch (error) {
        console.error("Error fetching jobs:", error);
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: error.message,
          background: 'linear-gradient(135deg, #0B6F78, #0a306b)',
          color: 'white'
        })
        setLoading(false);
      }
    };

    fetchJobs();
  }, []);

  // Filter jobs based on search and filters
  useEffect(() => {
    let filtered = jobs;

    // Search filter
    if (searchQuery) {
      filtered = filtered.filter(job =>
        job.title?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        job.skills?.some(skill => skill.toLowerCase().includes(searchQuery.toLowerCase())) ||
        job.description?.toLowerCase().includes(searchQuery.toLowerCase())
      );
    }

    // Job type filter
    if (activeFilter !== 'all') {
      filtered = filtered.filter(job => {
        const jobType = job.job_type?.toLowerCase();
        if (activeFilter === 'remote') return job.site_based === false;
        if (activeFilter === 'onsite') return job.site_based === true;
        if (activeFilter === 'full-time') return jobType === 'full time' || jobType === 'full-time';
        if (activeFilter === 'part-time') return jobType === 'part time' || jobType === 'part-time';
        return true;
      });
    }

    // Location filter
    if (locationFilter) {
      filtered = filtered.filter(job =>
        [job.city, job.province, job.country]
          .filter(Boolean)
          .join(", ")
          .toLowerCase()
          .includes(locationFilter.toLowerCase())
      );
    }

    setFilteredJobs(filtered);
  }, [searchQuery, activeFilter, locationFilter, jobs]);

  const jobTypes = [
    { id: 'all', label: 'All Jobs', icon: Briefcase },
    { id: 'remote', label: 'Remote', icon: MapPin },
    { id: 'onsite', label: 'On-Site', icon: MapPin },
    { id: 'full-time', label: 'Full Time', icon: Clock },
    { id: 'part-time', label: 'Part Time', icon: Clock }
  ];

  const stats = [
    { label: 'Total Jobs', value: jobs.length },
    { label: 'Remote Positions', value: jobs.filter(job => !job.site_based).length },
    { label: 'Open Roles', value: jobs.length } // Assuming all jobs are open
  ];

  return (
    <div 
      className="min-h-screen py-20"
      style={{
        background: 'linear-gradient(135deg, #0B6F7810, #0a306b20)'
      }}
    >
      <Container>
        {/* Hero Section */}
        <div className="text-center mb-16">
          <Heading level={1} className="text-4xl md:text-6xl font-bold mb-6">
            Join Our <span style={{ 
              background: 'linear-gradient(135deg, #0B6F78, #0a306b)',
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent'
            }}>Team</span>
          </Heading>
          <p className="text-gray-600 text-lg md:text-xl max-w-3xl mx-auto mb-8">
            Discover exciting career opportunities and be part of our mission to transform education worldwide.
          </p>

          {/* Stats */}
          <div className="grid grid-cols-3 gap-8 max-w-2xl mx-auto mb-8">
            {stats.map((stat, index) => (
              <div key={index} className="text-center">
                <div 
                  className="text-3xl font-bold mb-2"
                  style={{
                    background: 'linear-gradient(135deg, #0B6F78, #0a306b)',
                    WebkitBackgroundClip: 'text',
                    WebkitTextFillColor: 'transparent'
                  }}
                >
                  {stat.value}
                </div>
                <div className="text-gray-600 text-sm">{stat.label}</div>
              </div>
            ))}
          </div>

          {/* Search Bar */}
          <div className="max-w-4xl mx-auto mb-8">
            <div className="relative group">
              <div className="absolute inset-0 rounded-2xl p-[2px] opacity-80 transition-all duration-500 group-hover:scale-105 group-focus-within:scale-105 group-focus-within:opacity-100"
                   style={{
                     background: 'linear-gradient(135deg, #0B6F78, #0a306b)'
                   }}>
              </div>
              <div className="relative">
                <Search className="absolute left-6 top-1/2 transform -translate-y-1/2 text-gray-500 z-10 transition-colors duration-300 group-hover:text-[#0B6F78] group-focus-within:text-[#0B6F78]" />
                <input
                  type="text"
                  placeholder="Search jobs by title, skills, or keywords..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-16 pr-6 py-5 rounded-2xl border-2 border-transparent shadow-2xl focus:outline-none text-lg text-gray-800 transition-all duration-300 relative z-20 bg-white group-hover:bg-gray-50 group-focus-within:bg-white"
                />
              </div>
            </div>
          </div>

          {/* Location Filter */}
          <div className="max-w-md mx-auto mb-8">
            <div className="relative">
              <MapPin className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" />
              <input
                type="text"
                placeholder="Filter by location..."
                value={locationFilter}
                onChange={(e) => setLocationFilter(e.target.value)}
                className="w-full pl-12 pr-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-[#0B6F78] focus:border-transparent"
              />
            </div>
          </div>

          {/* Job Type Filters */}
          <div className="flex flex-wrap justify-center gap-4 mb-8">
            {jobTypes.map((type) => (
              <button
                key={type.id}
                onClick={() => setActiveFilter(type.id)}
                className={`flex items-center px-6 py-3 rounded-xl font-semibold transition-all duration-300 transform hover:scale-105 ${
                  activeFilter === type.id
                    ? 'text-white shadow-lg'
                    : 'text-gray-700 bg-white border border-gray-200 hover:border-[#0B6F78]'
                }`}
                style={
                  activeFilter === type.id 
                    ? { background: 'linear-gradient(135deg, #0B6F78, #0a306b)' }
                    : {}
                }
              >
                <type.icon className="w-4 h-4 mr-2" />
                {type.label}
              </button>
            ))}
          </div>
        </div>

        {/* Results Info */}
        <div className="text-center mb-8">
          <p className="text-gray-600">
            Showing {filteredJobs.length} of {jobs.length} jobs
            {searchQuery && ` for "${searchQuery}"`}
            {locationFilter && ` in ${locationFilter}`}
            {activeFilter !== 'all' && ` • ${jobTypes.find(t => t.id === activeFilter)?.label}`}
          </p>
        </div>

        {/* Jobs Grid */}
        {loading ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {Array.from({ length: 6 }).map((_, index) => (
              <div key={index} className="bg-white rounded-3xl shadow-lg animate-pulse p-6">
                <div className="w-full h-48 bg-gradient-to-br from-gray-200 to-gray-300 rounded-2xl mb-4"></div>
                <div className="h-6 bg-gray-300 rounded w-3/4 mb-4"></div>
                <div className="h-4 bg-gray-300 rounded w-full mb-2"></div>
                <div className="h-4 bg-gray-300 rounded w-5/6"></div>
              </div>
            ))}
          </div>
        ) : filteredJobs.length === 0 ? (
          <div className="text-center py-16">
            <div className="text-6xl mb-4">🔍</div>
            <div 
              className="text-2xl font-bold mb-2"
              style={{
                background: 'linear-gradient(135deg, #0B6F78, #0a306b)',
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent'
              }}
            >
              No jobs found
            </div>
            <p className="text-gray-500 max-w-md mx-auto">
              {searchQuery || locationFilter || activeFilter !== 'all' 
                ? 'Try adjusting your search criteria or filters.' 
                : 'No job openings are currently available. Check back later!'}
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {filteredJobs.map((job, index) => (
              <JobOpportunitiesfirst
                key={job.id || index}
                id={job.id}
                image={
                  job.image ||
                  "https://images.pexels.com/photos/3184465/pexels-photo-3184465.jpeg?auto=compress&cs=tinysrgb&w=800"
                }
                title={job.title}
                workType={[
                  job.job_type || "Full Time",
                  job.site_based ? "Onsite" : "Remote",
                ]}
                location={
                  [job.city, job.province, job.country]
                    .filter(Boolean)
                    .join(", ")
                }
                experience={job.experience}
                skills={job.skills || []}
              />
            ))}
          </div>
        )}

        {/* CTA Section */}
        {!loading && filteredJobs.length > 0 && (
          <div className="text-center mt-16">
            <div 
              className="rounded-3xl p-8 text-white shadow-2xl"
              style={{
                background: 'linear-gradient(135deg, #0B6F78, #0a306b)'
              }}
            >
              <h3 className="text-2xl font-bold mb-4">Can't Find Your Perfect Role?</h3>
              <p className="text-white/80 mb-6">Send us your resume and we'll notify you when matching positions open up.</p>
              <button className="bg-white text-[#0a306b] font-bold py-3 px-8 rounded-xl hover:bg-gray-100 transition-all duration-300 transform hover:scale-105">
                Submit Your Resume
              </button>
            </div>
          </div>
        )}
      </Container>
    </div>
  );
}

export default JobOpportunitiesorgan;