'use client';
import { AnimatePresence, motion } from 'framer-motion';
import {
  ArrowRight,
  Briefcase,
  Calendar,
  ChevronDown,
  ChevronUp,
  MapPin,
  Search,
} from 'lucide-react';
import Image from 'next/image';
import React, { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Skeleton } from '@/components/ui/skeleton';
import { ApplyDialog } from '@/components/web/job/ApplyDialog';
import WebLayout from '@/components/web/layout/web-layout';
import type { Job } from '@/db/schema';
import { cn } from '@/lib/utils';

const offer: Job = {
  id: '0',
  title: 'Send Open Application',
  location: 'Send Open Application',
  type: 'Full-time',
  department: 'Send Open Application',
  description: 'Send Open Application',
  postedDate: null,
  responsibilities: null,
  requirements: null,
  closingDate: null,
  status: null,
  closed: null,
  slug: '',
  createdAt: undefined,
  updatedAt: undefined,
};

const Careers = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [jobs, setJobs] = useState<Job[]>([]);
  const [galleries, setGalleries] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [locationFilter, setLocationFilter] = useState('all');
  const [departmentFilter, setDepartmentFilter] = useState('all');
  const [typeFilter, setTypeFilter] = useState('all');
  const [expandedJob, setExpandedJob] = useState<string | null>(null);

  const locations = [
    'all',
    ...Array.from(new Set(jobs.map((job) => job.location))),
  ];
  const departments = [
    'all',
    ...Array.from(new Set(jobs.map((job) => job.department))),
  ];
  const jobTypes = ['all', ...Array.from(new Set(jobs.map((job) => job.type)))];

  useEffect(() => {
    const loadJobs = async () => {
      setIsLoading(true);
      try {
        const res = await fetch('/api/jobs');
        const data = await res.json();

        setJobs(data);
      } catch (error) {
        console.error('Error loading jobs', error);
      } finally {
        setIsLoading(false);
      }
    };
    loadJobs();
  }, []);

  const filteredJobs = jobs.filter((job) => {
    const matchesSearch =
      job.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      job?.description.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesLocation =
      locationFilter === 'all' || job.location === locationFilter;
    const matchesDepartment =
      departmentFilter === 'all' || job.department === departmentFilter;
    const matchesType = typeFilter === 'all' || job.type === typeFilter;

    return matchesSearch && matchesLocation && matchesDepartment && matchesType;
  });

  const toggleJobExpansion = (jobId: string) => {
    if (expandedJob === jobId) {
      setExpandedJob(null);
    } else {
      setExpandedJob(jobId);
    }
  };

  const fetchGalleries = async () => {
    try {
      const response = await fetch('/api/photos/career');
      const data = await response.json();
      setGalleries(data);
    } catch (error) {
      conosole.log(`Error occur ${error}`);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchGalleries();
  }, []);

  // Get 15 random images from the galleries array
  const getRandomImages = () => {
    if (galleries.length <= 3) return galleries;

    // Shuffle array and take first 15
    const shuffled = [...galleries].sort(() => 0.5 - Math.random());
    return shuffled.slice(0, 3);
  };

  const randomImages = getRandomImages();

  const [bgImage, setBgImage] = useState<string>('');

  const fallbackImage = '/images/logo.png'; // Use your own fallback image URL

  useEffect(() => {
    let intervalId;

    if (Array.isArray(galleries) && galleries.length > 0) {
      const validImages = galleries
        .map((h) => h?.image?.trim())
        .filter((img) => img); // filter out empty or undefined images

      if (validImages.length > 1) {
        // Set an initial image
        setBgImage(validImages[Math.floor(Math.random() * validImages.length)]);

        intervalId = setInterval(() => {
          const randomImage =
            validImages[Math.floor(Math.random() * validImages.length)];
          setBgImage(randomImage);
        }, 3000); // change every 3 seconds
      } else {
        // Only one image or none available
        setBgImage(validImages[0] || fallbackImage);
      }
    } else {
      setBgImage(fallbackImage);
    }

    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, [galleries]);

  return (
    <WebLayout>
      <div>
        <section
          className="w-full bg-center bg-cover py-20 text-white"
          style={{
            backgroundImage: `linear-gradient(to right, rgba(0, 70, 173, 0.85), rgba(0, 160, 233, 0.85)), url(${bgImage})`,
          }}
        >
          <div className="container mx-auto px-4">
            <div className="max-w-3xl pt-12">
              <h1 className="mb-6 font-bold text-4xl md:text-5xl">
                Join Our Team
              </h1>
              <p className="text-white/90 text-xl">
                Discover exciting career opportunities at O.K. Isokariari
                Nigeria Limited and become part of a team dedicated to
                engineering excellence and innovation.
              </p>
            </div>
          </div>
        </section>

        <section className="bg-white py-16 text-black">
          <div className="container mx-auto px-4">
            <div className="mb-12 text-center">
              <h2 className="mb-6 font-bold text-3xl text-oki-gray-dark">
                Why Work With Us?
              </h2>
              <p className="mx-auto max-w-3xl text-gray-600 text-lg">
                At O.K. Isokariari Nigeria Limited, we offer more than just a
                job – we provide a career pathway with opportunities for growth,
                learning, and making a meaningful impact.
              </p>
            </div>

            <div className="grid grid-cols-1 gap-16 md:grid-cols-4">
              <div className="col-span-2 grid grid-cols-2 gap-3">
                <div className="rounded-lg bg-white p-6 shadow-md transition-shadow hover:shadow-lg">
                  <div className="mb-4 text-4xl">🚀</div>
                  <h3 className="mb-3 font-semibold text-oki-gray-dark text-xl">
                    Career Growth
                  </h3>
                  <p className="text-gray-600">
                    Clear advancement paths and opportunities for professional
                    development at all levels.
                  </p>
                </div>

                <div className="rounded-lg bg-white p-6 shadow-md transition-shadow hover:shadow-lg">
                  <div className="mb-4 text-4xl">🎓</div>
                  <h3 className="mb-3 font-semibold text-oki-gray-dark text-xl">
                    Continuous Learning
                  </h3>
                  <p className="text-gray-600">
                    Training programs, workshops, and education support to
                    enhance your skills and knowledge.
                  </p>
                </div>

                <div className="rounded-lg bg-white p-6 shadow-md transition-shadow hover:shadow-lg">
                  <div className="mb-4 text-4xl">🌟</div>
                  <h3 className="mb-3 font-semibold text-oki-gray-dark text-xl">
                    Impactful Projects
                  </h3>
                  <p className="text-gray-600">
                    Work on significant infrastructure projects that shape
                    Nigeria's development and improve lives.
                  </p>
                </div>

                <div className="rounded-lg bg-white p-6 shadow-md transition-shadow hover:shadow-lg">
                  <div className="mb-4 text-4xl">👥</div>
                  <h3 className="mb-3 font-semibold text-oki-gray-dark text-xl">
                    Collaborative Culture
                  </h3>
                  <p className="text-gray-600">
                    A supportive team environment that values diversity,
                    innovation, and mutual respect.
                  </p>
                </div>
              </div>
              <div className="relative col-span-2 h-full min-h-[500px]">
                <AnimatePresence>
                  {randomImages.map((gallery, index) => (
                    <motion.div
                      animate={{ opacity: 1, y: 0 }}
                      className={cn(
                        'absolute overflow-hidden rounded-lg shadow-lg',
                        index === 0 && 'top-0 right-10 z-10 w-2/4',
                        index === 1 && 'top-[160px] left-0 z-20 w-2/4',
                        index === 2 && 'top-2/3 right-28 z-30 w-2/5'
                      )}
                      initial={{ opacity: 0, y: 20 }}
                      key={gallery.id}
                      transition={{ delay: index * 0.2 }}
                    >
                      <Image
                        alt={gallery.title || 'Gallery image'}
                        className="h-full w-full object-cover"
                        height={50}
                        src={gallery.url}
                        width={50}
                      />
                      <div className="absolute right-0 bottom-0 left-0 bg-gradient-to-t from-black/80 to-transparent p-4">
                        <h3 className="font-semibold text-white">
                          {gallery.title}
                        </h3>
                        <p className="line-clamp-1 text-sm text-white/80">
                          {gallery.description}
                        </p>
                      </div>
                    </motion.div>
                  ))}
                </AnimatePresence>
              </div>
            </div>
          </div>
        </section>

        <section className="bg-oki-gray-light py-16">
          <div className="container mx-auto px-4">
            <h2 className="mb-8 font-bold text-3xl text-oki-gray-dark">
              Current Opportunities
            </h2>

            <div className="mb-8 rounded-lg bg-white p-6 shadow-md">
              <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
                <div className="relative">
                  <Search
                    className="-translate-y-1/2 absolute top-1/2 left-3 transform text-gray-500"
                    size={18}
                  />
                  <Input
                    className="pl-10"
                    onChange={(e) => setSearchTerm(e.target.value)}
                    placeholder="Search jobs..."
                    type="text"
                    value={searchTerm}
                  />
                </div>

                <div>
                  <select
                    className="w-full rounded-md border border-gray-300 p-2 focus:outline-none focus:ring-2 focus:ring-oki-blue-dark"
                    onChange={(e) => setLocationFilter(e.target.value)}
                    value={locationFilter}
                  >
                    <option key="all-location" value="all">
                      All Locations
                    </option>
                    {locations
                      .filter((loc) => loc !== 'all')
                      .map((location) => (
                        <option key={`location-${location}`} value={location}>
                          {location}
                        </option>
                      ))}
                  </select>
                </div>

                <div>
                  <select
                    className="w-full rounded-md border border-gray-300 p-2 focus:outline-none focus:ring-2 focus:ring-oki-blue-dark"
                    onChange={(e) => setDepartmentFilter(e.target.value)}
                    value={departmentFilter}
                  >
                    <option value="all">All Departments</option>
                    {departments
                      .filter((dept) => dept !== 'all')
                      .map((department) => (
                        <option key={`dept-${department}`} value={department}>
                          {department}
                        </option>
                      ))}
                  </select>
                </div>

                <div>
                  <select
                    className="w-full rounded-md border border-gray-300 p-2 focus:outline-none focus:ring-2 focus:ring-oki-blue-dark"
                    onChange={(e) => setTypeFilter(e.target.value)}
                    value={typeFilter}
                  >
                    <option value="all">All Job Types</option>
                    {jobTypes
                      .filter((type) => type !== 'all')
                      .map((jobType) => (
                        <option key={`type-${jobType}`} value={jobType}>
                          {jobType}
                        </option>
                      ))}
                  </select>
                </div>
              </div>
            </div>

            {isLoading ? (
              <motion.div
                animate={{ opacity: 1 }}
                className="space-y-4"
                exit={{ opacity: 0 }}
                initial={{ opacity: 0 }}
              >
                {[...Array(3)].map((_, i) => (
                  <Skeleton className="h-40 w-full rounded-lg" key={i} />
                ))}
              </motion.div>
            ) : (
              <motion.div
                animate={{ opacity: 1 }}
                className="space-y-6"
                exit={{ opacity: 0 }}
                initial={{ opacity: 0 }}
              >
                <AnimatePresence mode="popLayout">
                  {filteredJobs.length > 0 ? (
                    filteredJobs.map((job, index) => (
                      <motion.div
                        animate={{ opacity: 1, y: 0 }}
                        className="overflow-hidden rounded-lg bg-white shadow-md"
                        exit={{ opacity: 0, y: -20 }}
                        initial={{ opacity: 0, y: 20 }}
                        key={job.id || `job-${index}`}
                        layout
                        transition={{ delay: index * 0.1, duration: 0.3 }}
                      >
                        <div
                          className="cursor-pointer p-6"
                          onClick={() => toggleJobExpansion(job.id)}
                        >
                          <div className="flex flex-col md:flex-row md:items-center md:justify-between">
                            <div className="mb-4 md:mb-0">
                              <h3 className="font-semibold text-oki-gray-dark text-xl">
                                {job.title}
                              </h3>
                              <p className="text-oki-blue-dark">
                                {job.department}
                              </p>
                            </div>
                            <div className="flex flex-wrap gap-3">
                              <div className="flex items-center text-gray-600 text-sm">
                                <MapPin className="mr-1" size={14} />
                                <span>{job.location}</span>
                              </div>
                              <div className="flex items-center text-gray-600 text-sm">
                                <Briefcase className="mr-1" size={14} />
                                <span>{job.type}</span>
                              </div>
                              {/* <div className="flex items-center text-gray-600 text-sm">
                                <Calendar size={14} className="mr-1" />
                                <span>Posted: {job.posted_date}</span>
                              </div> */}
                              <div className="flex items-center text-gray-600 text-sm">
                                <Calendar className="mr-1" size={14} />
                                <span>Closing: {job?.closingDate}</span>
                              </div>
                              <Button
                                className="ml-2"
                                size="icon"
                                variant="ghost"
                              >
                                {expandedJob === job.id ? (
                                  <ChevronUp size={20} />
                                ) : (
                                  <ChevronDown size={20} />
                                )}
                              </Button>
                            </div>
                          </div>
                        </div>
                        <div
                          className={cn(
                            'overflow-hidden transition-all duration-300',
                            expandedJob === job.id
                              ? 'max-h-[2000px] opacity-100'
                              : 'max-h-0 opacity-0'
                          )}
                        >
                          <div className="border-gray-200 border-t p-6">
                            {job.description && (
                              <div className="mb-6">
                                <h4 className="mb-3 font-semibold text-lg text-oki-gray-dark">
                                  Job Descriptions:
                                </h4>
                                <div
                                  className="prose prose-lg max-w-none text-oki-gray-dark"
                                  dangerouslySetInnerHTML={{
                                    __html: job.description,
                                  }}
                                />
                              </div>
                            )}
                            {job.responsibilities && (
                              <div className="mb-6">
                                <h4 className="mb-3 font-semibold text-lg text-oki-gray-dark">
                                  Job Responsibilities:
                                </h4>
                                <div
                                  className="prose prose-lg max-w-none text-oki-gray-dark"
                                  dangerouslySetInnerHTML={{
                                    __html: job.responsibilities,
                                  }}
                                />
                              </div>
                            )}
                            {job.requirements && (
                              <div className="mb-6">
                                <h4 className="mb-3 font-semibold text-lg text-oki-gray-dark">
                                  Job Descriptions:
                                </h4>
                                <div
                                  className="prose prose-lg max-w-none text-oki-gray-dark"
                                  dangerouslySetInnerHTML={{
                                    __html: job.requirements,
                                  }}
                                />
                              </div>
                            )}
                            <ApplyDialog job={job} label="Apply Now" />
                          </div>
                        </div>
                      </motion.div>
                    ))
                  ) : (
                    <motion.div
                      animate={{ opacity: 1 }}
                      className="rounded-lg bg-white p-8 text-center shadow-md"
                      exit={{ opacity: 0 }}
                      initial={{ opacity: 0 }}
                    >
                      <h3 className="mb-4 font-semibold text-oki-gray-dark text-xl">
                        No positions found
                      </h3>
                      <p className="mb-6 text-gray-600">
                        There are no positions matching your search criteria at
                        this time.
                      </p>
                      <Button
                        className="border-oki-blue-dark text-oki-blue-dark hover:bg-oki-blue-dark hover:text-white"
                        onClick={() => {
                          setSearchTerm('');
                          setLocationFilter('all');
                          setDepartmentFilter('all');
                          setTypeFilter('all');
                        }}
                        variant="outline"
                      >
                        Clear Filters
                      </Button>
                    </motion.div>
                  )}
                </AnimatePresence>
              </motion.div>
            )}
          </div>
        </section>

        <section className="bg-white py-16 text-black">
          <div className="container mx-auto px-4">
            <div className="mb-12 text-center">
              <h2 className="mb-6 font-bold text-3xl text-oki-gray-dark">
                Our Application Process
              </h2>
              <p className="mx-auto max-w-3xl text-gray-600 text-lg">
                We've designed a straightforward application process to help you
                find the right opportunity with O.K. Isokariari Nigeria Limited.
              </p>
            </div>

            <div className="grid grid-cols-1 gap-6 md:grid-cols-4">
              <div className="relative rounded-lg bg-white p-6 shadow-md">
                <div className="-top-4 -translate-x-1/2 absolute left-1/2 flex h-8 w-8 transform items-center justify-center rounded-full bg-oki-blue-dark font-bold text-white">
                  1
                </div>
                <h3 className="mt-4 mb-3 text-center font-semibold text-oki-gray-dark text-xl">
                  Application
                </h3>
                <p className="text-center text-gray-600">
                  Submit your application through our online portal with your
                  resume and cover letter.
                </p>
              </div>

              <div className="relative rounded-lg bg-white p-6 shadow-md">
                <div className="-top-4 -translate-x-1/2 absolute left-1/2 flex h-8 w-8 transform items-center justify-center rounded-full bg-oki-blue-dark font-bold text-white">
                  2
                </div>
                <h3 className="mt-4 mb-3 text-center font-semibold text-oki-gray-dark text-xl">
                  Screening
                </h3>
                <p className="text-center text-gray-600">
                  Our HR team reviews applications and conducts initial phone
                  interviews with promising candidates.
                </p>
              </div>

              <div className="relative rounded-lg bg-white p-6 shadow-md">
                <div className="-top-4 -translate-x-1/2 absolute left-1/2 flex h-8 w-8 transform items-center justify-center rounded-full bg-oki-blue-dark font-bold text-white">
                  3
                </div>
                <h3 className="mt-4 mb-3 text-center font-semibold text-oki-gray-dark text-xl">
                  Interviews
                </h3>
                <p className="text-center text-gray-600">
                  Selected candidates participate in technical and cultural fit
                  interviews with the hiring team.
                </p>
              </div>

              <div className="relative rounded-lg bg-white p-6 shadow-md">
                <div className="-top-4 -translate-x-1/2 absolute left-1/2 flex h-8 w-8 transform items-center justify-center rounded-full bg-oki-blue-dark font-bold text-white">
                  4
                </div>
                <h3 className="mt-4 mb-3 text-center font-semibold text-oki-gray-dark text-xl">
                  Offer
                </h3>
                <p className="text-center text-gray-600">
                  Successful candidates receive an offer and begin their journey
                  with O.K. Isokariari Nigeria Limited.
                </p>
              </div>
            </div>
          </div>
        </section>

        <section className="bg-oki-blue-dark py-16 text-white">
          <div className="container mx-auto px-4 text-center">
            <h2 className="mb-6 font-bold text-3xl">
              Didn't See a Perfect Match?
            </h2>
            <p className="mx-auto mb-8 max-w-2xl text-lg text-white/80">
              We're always looking for talented individuals to join our team.
              Submit your resume for future opportunities.
            </p>
            <ApplyDialog job={offer} label="Send Open Application" />
          </div>
        </section>
      </div>
    </WebLayout>
  );
};

export default Careers;
