'use client';

import { motion } from 'framer-motion';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import type { Equipment } from '@/db/schema';
import ClientsCarousel from '@/components/web/home/ClientsCarousel';

const fadeIn = {
  hidden: { opacity: 0, y: 20 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.6 },
  },
};

const staggerContainer = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: {
      staggerChildren: 0.2,
    },
  },
};

export default function Equipments() {
  const [equipmentsData, setEquipmentsData] = useState<Equipment[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [bgImage, setBgImage] = useState<string>('/images/placeholder.svg');

  useEffect(() => {
    const fetchEquipments = async () => {
      setIsLoading(true);
      try {
        const response = await fetch('/api/equipments');

        const data = await response.json();
        setEquipmentsData(data);
      } catch (error) {
        console.error('Failed to fetch equipments:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchEquipments();
  }, []);

  useEffect(() => {
    if (Array.isArray(equipmentsData) && equipmentsData.length > 0) {
      const randomPost =
        equipmentsData[Math.floor(Math.random() * equipmentsData.length)];
      const image = randomPost?.image?.trim() || '';
      setBgImage(image !== '' ? image : '/images/placeholder.svg');
    } else {
      setBgImage('/images/placeholder.svg');
    }
  }, [equipmentsData]);

  return (
    <>
      <style>{`
        .about-hero-bg {
          background-image: linear-gradient(
              to right,
              rgba(0, 70, 173, 0.85),
              rgba(0, 160, 233, 0.85)
            ),
            url(${bgImage});
          background-size: cover;
          background-position: center;
        }
      `}</style>
      <div className="">
        {/* Hero Section */}
        <section className="about-hero-bg py-20 pt-32 text-white">
          <div className="container mx-auto px-4">
            <motion.div
              animate="visible"
              className="max-w-3xl"
              initial="hidden"
              variants={fadeIn}
            >
              <h1 className="mb-6 font-bold text-4xl md:text-5xl">
                Our Equipments
              </h1>
              <p className="mb-4 text-white/90 text-xl leading-relaxed">
                At O.K. Isokariari Nigeria Limited (O.K.I), we pride ourselves
                on maintaining a modern, diverse, and reliable fleet of
                equipment to handle a wide range of construction, earthmoving,
                and transportation projects. Our machines are operated by
                skilled professionals and maintained to the highest standards to
                ensure performance, safety, and efficiency on every job.
              </p>
            </motion.div>
          </div>
        </section>

        {/* Meet Our Top Management Section */}
        <section className="bg-oki-gray-light py-16">
          <div className="container mx-auto px-4">
            <div className="mb-12 text-center" />

            <div className="grid grid-cols-1 gap-8 md:grid-cols-1">
              {isLoading ? (
                <div className="grid grid-cols-1 gap-8">
                  {Array.from({ length: 3 }).map((_, i) => (
                    <div
                      className="grid grid-cols-2 items-center overflow-hidden rounded-lg bg-white shadow-md"
                      key={i}
                    >
                      <Skeleton className="h-86 w-full" />
                      <div className="space-y-4 p-6">
                        <Skeleton className="h-6 w-3/4" />
                        <Skeleton className="h-4 w-1/2" />
                        <Skeleton className="h-4 w-full" />
                      </div>
                    </div>
                  ))}
                </div>
              ) : equipmentsData.length === 0 ? (
                <div>No equipments found.</div>
              ) : (
                equipmentsData.map((member, index) => {
                  const isImageLeft = index % 2 === 0;
                  return (
                    <motion.div
                      className="grid grid-cols-2 items-center overflow-hidden rounded-lg bg-white shadow-lg transition-shadow hover:shadow-xl"
                      key={index}
                      variants={fadeIn}
                      viewport={{ once: false }}
                    >
                      {isImageLeft && (
                        <motion.div
                          className="h-86 overflow-hidden"
                          initial={{ opacity: 0, x: 230 }}
                          viewport={{ once: false }}
                          whileInView={{ opacity: 1, x: 0 }}
                        >
                          <img
                            alt={member.name}
                            className="h-full w-full object-cover object-center"
                            src={member.image}
                          />
                        </motion.div>
                      )}
                      <div className="p-6">
                        <h3 className="font-bold text-oki-gray-dark text-xl">
                          {member.name}
                        </h3>

                        <p className="text-gray-600">{member.content}</p>
                      </div>
                      {!isImageLeft && (
                        <motion.div
                          className="h-86 overflow-hidden"
                          initial={{ opacity: 0, x: -230 }}
                          viewport={{ once: false, amount: 0.4 }}
                          whileInView={{ opacity: 1, x: 0 }}
                        >
                          <img
                            alt={member.name}
                            className="h-full w-full object-cover object-center"
                            src={member.image}
                          />
                        </motion.div>
                      )}
                    </motion.div>
                  );
                })
              )}
            </div>
          </div>
        </section>

        {/* Clients Carousel Section */}
        <ClientsCarousel />

        {/* CTA Section */}
        <section className="bg-gradient-to-r from-oki-blue-dark to-oki-blue-light py-16 text-white">
          <div className="container mx-auto px-4 text-center">
            <motion.div
              animate={{ opacity: 1, y: 0 }}
              initial={{ opacity: 0, y: 30 }}
              transition={{ duration: 0.7 }}
              viewport={{ once: false }}
            >
              <h2 className="mb-6 font-bold text-3xl">
                Ready to Work With Us?
              </h2>
              <p className="mx-auto mb-8 max-w-2xl text-lg text-white/80">
                Whether you're looking for a construction partner, career
                opportunities, or more information about our services, we'd love
                to hear from you.
              </p>
              <div className="flex flex-col justify-center gap-4 sm:flex-row">
                <Link href="/contact">
                  <Button className="bg-white px-8 py-6 text-oki-blue-dark hover:bg-white/90">
                    Contact Us
                  </Button>
                </Link>
                <Link href="/team">
                  <Button
                    className="border-white px-8 py-6 text-white hover:bg-white/10"
                    variant="outline"
                  >
                    Meet Our Equipment
                  </Button>
                </Link>
              </div>
            </motion.div>
          </div>
        </section>
      </div>
    </>
  );
}
