'use client';

import { motion } from 'framer-motion';
import { ArrowRight } from 'lucide-react';
import Image from 'next/image';
import Link from 'next/link';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import WebLayout from '@/components/web/layout/web-layout';
import { useServicesStore } from '@/stores/useServicesStore';

const Services = () => {
  const { services, loadingServices, fetchServices } = useServicesStore();

  useEffect(() => {
    if (!services) {
      fetchServices();
    }
  }, [services, fetchServices]);

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

  useEffect(() => {
    if (!Array.isArray(services)) {
      setBgImage(fallbackImage);
      return;
    }

    const validImages = services
      .map((service) => service?.image?.trim())
      .filter(Boolean);

    if (validImages.length === 0) {
      setBgImage(fallbackImage);
      return;
    }

    if (validImages.length === 1) {
      setBgImage(validImages[0]);
      return;
    }

    // For multiple images
    const getRandomImage = () =>
      validImages[Math.floor(Math.random() * validImages.length)];

    setBgImage(getRandomImage());

    const intervalId = setInterval(() => {
      setBgImage(getRandomImage());
    }, 8000);

    return () => clearInterval(intervalId);
  }, [services]);

  return (
    <WebLayout>
      {/* 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">
          <div className=" max-w-3xl">
            <h1 className="mt-12 mb-6 font-bold text-4xl md:text-5xl">
              Our Services
            </h1>
            <p className="text-white/90 text-xl">
              With over five decades of experience, we provide comprehensive
              engineering and construction services to meet the diverse needs of
              our clients.
            </p>
          </div>
        </div>
      </section>

      {/* Services Grid */}
      <section className="bg-white py-16">
        <div className="container px-4">
          {loadingServices ? (
            <div className="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3">
              {Array.from({ length: 6 }).map((_, index) => (
                <Skeleton className="h-72 rounded-lg shadow-md" key={index} />
              ))}
            </div>
          ) : services?.length === 0 ? (
            <div className="py-16 text-center">
              <h3 className="font-semibold text-2xl text-gray-800">
                No services found
              </h3>
              <p className="mt-2 text-gray-600">
                There are no services to display at the moment.
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3">
              {services?.map((service, index) => (
                <motion.div
                  className="group relative h-72 overflow-hidden rounded-lg shadow-md"
                  initial={{ opacity: 0, y: -50 }}
                  key={service.id}
                  transition={{ delay: index * 0.1, duration: 0.5 }}
                  viewport={{ once: true }}
                  whileInView={{ opacity: 1, y: 0 }}
                >
                  <Image
                    alt={service?.name}
                    className="h-full w-full rounded-lg object-cover transition-transform duration-500 group-hover:scale-105"
                    height={500}
                    src={service.image || '/placeholder.jpg'}
                    width={500}
                  />
                  <div
                    className="absolute inset-0 flex flex-col items-center justify-center p-6 opacity-0 transition-opacity duration-300 group-hover:opacity-100"
                    style={{ backgroundColor: 'rgba(0, 0, 0, 0.5)' }}
                  >
                    <Link
                      className="flex items-center justify-center gap-2 font-semibold text-white uppercase"
                      href={`/services/${service.id}`}
                    >
                      <div className="font-bold text-lg">{service.name}</div>
                    </Link>
                    <div className="mt-4 text-center text-white">
                      <p className="mb-4 line-clamp-5">{service.summary}</p>
                      <Link
                        className="flex items-center justify-center gap-2 font-semibold text-white underline"
                        href={`/services/${service.id}`}
                      >
                        Learn More <ArrowRight size={16} />
                      </Link>
                    </div>
                  </div>
                </motion.div>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* CTA Section */}
      <section className="bg-oki-gray-light py-16 text-black">
        <div className="container px-4 text-center">
          <h2 className="mb-6 font-bold text-3xl text-[hsl(var(--oki-gray-dark))]">
            Need a Customized Solution?
          </h2>
          <p className="mx-auto mb-8 max-w-2xl text-[hsl(var(--muted-foreground))] text-lg">
            Our team of experts is ready to work with you to develop tailored
            solutions for your specific project requirements.
          </p>
          <Link href="/contact">
            <Button className="bg-oki-red px-8 py-6 text-white transition-all hover:bg-oki-blue-dark *:hover:bg-oki-blue-light">
              Request a Consultation
            </Button>
          </Link>
        </div>
      </section>
    </WebLayout>
  );
};

export default Services;
