'use client';
import { motion } from 'framer-motion';
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 type { Client, Project } from '@/db/schema';

export default function Clients() {
  const [clientsData, setClientsData] = useState<Client[]>([]);
  const [projectsData, setProjectsData] = useState<Project[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [bgImage, setBgImage] = useState<string>('/images/placeholder.svg');

  useEffect(() => {
    const fetchClientsAndProjects = async () => {
      setIsLoading(true);
      try {
        const [clientsRes, projectsRes] = await Promise.all([
          fetch('/api/clients'),
          fetch('/api/projects'),
        ]);

        const clients = await clientsRes.json();
        const projects = await projectsRes.json();

        setClientsData(clients);
        setProjectsData(projects);
      } catch (error) {
        console.error('Failed to fetch data:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchClientsAndProjects();
  }, []);

  // Combine clients with their projects
  const clientsWithProjects = clientsData.map((client) => ({
    ...client,
    projects: projectsData.filter((project) => project.clientId === client.id),
  }));

  // Background image logic
  useEffect(() => {
    if (Array.isArray(clientsData) && clientsData.length > 0) {
      const validImages = clientsData
        .map((c) => c?.image?.trim())
        .filter((img) => img);

      if (validImages.length > 0) {
        setBgImage(validImages[Math.floor(Math.random() * validImages.length)]);
      } else {
        setBgImage('/images/placeholder.svg');
      }
    } else {
      setBgImage('/images/placeholder.svg');
    }
  }, [clientsData]);

  return (
    <WebLayout>
      <style>{`
        .team-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>

      {/* Hero Section */}
      <section className="team-hero-bg py-20 pt-32 text-white">
        <div className="container mx-auto px-4">
          <div className="max-w-3xl">
            <h1 className="mb-6 font-bold text-4xl md:text-5xl">Our Clients</h1>
            <p className="text-white/90 text-xl leading-relaxed">
              For over five decades, we've built trust and delivered excellence
              to a diverse range of clients across Nigeria and beyond. Discover
              the companies and organizations that have partnered with O.K.
              Isokariari Nigeria Limited.
            </p>
          </div>
        </div>
      </section>

      {/* Clients Grid */}
      <section className="py-16">
        <div className="container mx-auto px-4">
          {isLoading ? (
            <div className="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3">
              {Array.from({ length: 6 }).map((_, i) => (
                <div
                  className="flex flex-col items-center overflow-hidden rounded-lg bg-white p-8 shadow-md"
                  key={i}
                >
                  <Skeleton className="mb-6 h-48 w-48 rounded-full" />
                  <Skeleton className="mb-3 h-8 w-3/4" />
                  <Skeleton className="mb-4 h-5 w-full" />
                  <Skeleton className="h-5 w-1/2" />
                </div>
              ))}
            </div>
          ) : (
            <div className="grid grid-cols-1 gap-8 md:grid-cols-2 lg:grid-cols-3">
              {clientsWithProjects.map((client) => (
                <motion.div
                  className="overflow-hidden rounded-lg bg-white shadow-md transition-all hover:shadow-xl"
                  initial={{ opacity: 0, y: 20 }}
                  key={client.id}
                  transition={{ duration: 0.5 }}
                  viewport={{ once: true }}
                  whileInView={{ opacity: 1, y: 0 }}
                >
                  <div className="flex flex-col items-center p-8">
                    <div className="mb-6 flex h-48 w-48 items-center justify-center overflow-hidden">
                      <Image
                        alt={`${client.name} logo`}
                        className="max-h-full max-w-full object-contain"
                        height={192}
                        src={client.image}
                        width={192}
                      />
                    </div>
                    <h2 className="mb-3 text-center font-bold text-2xl text-oki-gray-dark">
                      {client.name}
                    </h2>
                    <p className="mb-4 text-center text-gray-600">
                      {client.content}
                    </p>
                    {client.projects.length > 0 && (
                      <div className="mt-4 w-full">
                        <h3 className="mb-2 font-semibold text-oki-gray-dark text-sm">
                          Projects
                        </h3>
                        <div className="flex flex-wrap gap-2">
                          {client.projects.map(
                            (project: any, index: number) => (
                              <Link
                                href={`/projects/${project.slug}`}
                                key={index}
                              >
                                <span className="line-clamp-2 rounded bg-oki-blue-light/10 px-2 py-1 text-oki-blue-dark text-xs">
                                  {project.title}
                                </span>
                              </Link>
                            )
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </motion.div>
              ))}
            </div>
          )}

          {!isLoading && clientsWithProjects.length === 0 && (
            <div className="py-16 text-center">
              <h3 className="font-semibold text-2xl text-gray-800">
                No clients found
              </h3>
              <p className="mt-2 text-gray-600">
                There are no clients in this category.
              </p>
            </div>
          )}
        </div>
      </section>

      {/* CTA Section */}
      <section className="bg-oki-gray-dark py-16 text-white">
        <div className="container mx-auto px-4 text-center">
          <h2 className="mb-6 font-bold text-3xl">Become Our Client</h2>
          <p className="mx-auto mb-8 max-w-2xl text-lg text-white/80">
            Join our growing list of satisfied clients and experience the
            exceptional quality and service that O.K. Isokariari Nigeria Limited
            is known for.
          </p>
          <Button className="rounded bg-oki-blue-dark px-8 py-3 font-medium text-white transition-colors hover:bg-oki-blue-light">
            Contact Us Today
          </Button>
        </div>
      </section>
    </WebLayout>
  );
}
