'use client';

import { AnimatePresence, motion } from 'framer-motion';
import { ArrowRight } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { Button } from '@/components/ui/button';
import ClientsCarousel from '@/components/web/home/ClientsCarousel';
import WebLayout from '@/components/web/layout/web-layout';
import type { Project } from '@/db/schema';
import { cn } from '@/lib/utils';
import { useProjectsStore } from '@/stores/useProjectsStore';

const Projects = () => {
  const { projects, loadingProjects, fetchProjects } = useProjectsStore();
  const [filter, setFilter] = useState<string>('all');

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

  const categories = useMemo(() => {
    const uniqueCategories =
      projects && Array.isArray(projects)
        ? Array.from(new Set(projects.map((p) => p.category))).map(
            (category, index) => ({
              id: String(index + 1),
              name: category?.replace(/-/g, ' '),
              slug: category,
            })
          )
        : [];

    return [
      { id: 'all', name: 'All Projects', slug: 'all' },
      ...uniqueCategories,
    ];
  }, [projects]);

  const filteredProjects: Project[] =
    filter === 'all'
      ? projects || []
      : (projects || []).filter((project) => project.category === filter);

  const [bgImage, setBgImage] = useState<string>('');
  const fallbackImage = '/images/logo.png';

  useEffect(() => {
    let intervalId: NodeJS.Timeout;

    if (Array.isArray(projects) && projects.length > 0) {
      const validImages = projects
        .map((h) => h?.image?.trim())
        .filter((img) => img);

      if (validImages.length > 1) {
        setBgImage(validImages[Math.floor(Math.random() * validImages.length)]);

        intervalId = setInterval(() => {
          const randomImage =
            validImages[Math.floor(Math.random() * validImages.length)];
          setBgImage(randomImage);
        }, 3000);
      } else {
        setBgImage(validImages[0] || fallbackImage);
      }
    } else {
      setBgImage(fallbackImage);
    }

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

  return (
    <WebLayout>
      <div>
        {/* Hero Section */}
        <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 px-4 py-20 ">
            <div className="max-w-3xl">
              <h1 className="mb-6 font-bold text-4xl md:text-5xl">
                Our Projects
              </h1>
              <p className="text-white/90 text-xl">
                Explore our diverse portfolio of successful projects across
                Nigeria, showcasing our expertise in various construction and
                engineering fields.
              </p>
            </div>
          </div>

          {/* Category Filter */}
          <div className="container px-4 pb-10">
            <div className="flex flex-wrap justify-center gap-4">
              {categories.map((category, index) => (
                <motion.div
                  key={`${category.id}-${index}`}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <Button
                    className={cn(
                      'border',
                      filter === category.slug
                        ? 'border-white bg-white text-oki-blue-dark'
                        : 'border-white/50 bg-transparent text-white hover:bg-white/10'
                    )}
                    onClick={() => setFilter(category?.slug)}
                    variant="ghost"
                  >
                    {category.name}
                  </Button>
                </motion.div>
              ))}
            </div>
          </div>
        </section>

        {/* Project Grid */}
        <section className="bg-white py-16 text-black">
          <div className="container px-4">
            {loadingProjects ? (
              <div className="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3">
                {Array.from({ length: 6 }).map((_, i) => (
                  <div
                    className="h-[400px] animate-pulse rounded-lg bg-white shadow-md"
                    key={i}
                  >
                    <div className="h-64 w-full bg-gray-200" />
                    <div className="space-y-4 p-6">
                      <div className="h-4 w-1/3 rounded bg-gray-300" />
                      <div className="h-6 w-2/3 rounded bg-gray-300" />
                      <div className="h-4 w-full rounded bg-gray-200" />
                      <div className="h-4 w-5/6 rounded bg-gray-200" />
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <>
                <AnimatePresence mode="wait">
                  <motion.div
                    animate={{ opacity: 1 }}
                    className="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3"
                    exit={{ opacity: 0 }}
                    initial={{ opacity: 0 }}
                    key={filter}
                    transition={{ duration: 0.3 }}
                  >
                    {filteredProjects.map((project, index) => (
                      <motion.div
                        animate={{ opacity: 1, y: 0 }}
                        className="group overflow-hidden rounded-lg bg-white shadow-md transition-shadow hover:shadow-xl"
                        initial={{ opacity: 0, y: 20 }}
                        key={project.id}
                        layout
                        transition={{ duration: 0.4, delay: index * 0.1 }}
                      >
                        <div className="h-64 overflow-hidden">
                          <Image
                            alt={project.title}
                            className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
                            height={400}
                            onError={() => setBgImage(fallbackImage)}
                            src={project?.image}
                            width={600}
                          />
                        </div>
                        <div className="p-6">
                          <div className="mb-3">
                            <span className="rounded-full bg-oki-gray-light px-3 py-1 text-oki-gray-dark text-sm capitalize">
                              {project.category?.replace('-', ' ')}
                            </span>
                          </div>
                          <Link
                            className="flex items-center font-medium text-oki-blue-dark transition-colors hover:text-oki-blue-light"
                            href={`/projects/${project.id}`}
                          >
                            <h3 className="mb-3 line-clamp-4 font-semibold text-2xl text-oki-gray-dark">
                              {project.title}
                            </h3>
                          </Link>
                          <p className="mb-4 line-clamp-6 text-muted-foreground">
                            {project.description}
                          </p>
                          <Link
                            className="flex items-center font-medium text-oki-blue-dark transition-colors hover:text-[hsl(var(--oki-blue-light))]"
                            href={`/projects/${project.id}`}
                          >
                            <span>View Project</span>
                            <ArrowRight className="ml-2" size={16} />
                          </Link>
                        </div>
                      </motion.div>
                    ))}
                  </motion.div>
                </AnimatePresence>

                {filteredProjects.length === 0 && (
                  <motion.div
                    animate={{ opacity: 1 }}
                    className="py-12 text-center"
                    initial={{ opacity: 0 }}
                    transition={{ duration: 0.5 }}
                  >
                    <h3 className="mb-4 font-semibold text-2xl text-oki-gray-dark">
                      No projects found
                    </h3>
                    <p className="text-muted-foreground">
                      There are no projects in this category at the moment.
                    </p>
                  </motion.div>
                )}
              </>
            )}
          </div>
        </section>
        <ClientsCarousel />
        <section className="bg-oki-gray-dark py-16 text-white">
          <div className="container px-4 text-center">
            <h2 className="mb-6 font-bold text-3xl">Have a Project in Mind?</h2>
            <p className="mx-auto mb-8 max-w-2xl text-lg text-white/80">
              We're ready to bring your vision to life with our expertise and
              five decades of construction excellence.
            </p>
            <Link href="/contact">
              <Button className="bg-oki-red px-8 py-6 text-white hover:bg-oki-red/0.9">
                Discuss Your Project
              </Button>
            </Link>
          </div>
        </section>
      </div>
    </WebLayout>
  );
};

export default Projects;
