'use client';

import { ArrowLeft, ArrowRight, Calendar, MapPin } from 'lucide-react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import Lightbox from 'yet-another-react-lightbox';
import Captions from 'yet-another-react-lightbox/plugins/captions';

import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import 'yet-another-react-lightbox/plugins/captions.css';
import Thumbnails from 'yet-another-react-lightbox/plugins/thumbnails';
import 'yet-another-react-lightbox/plugins/thumbnails.css';
import 'yet-another-react-lightbox/styles.css';
import Image from 'next/image';
import WebLayout from '@/components/web/layout/web-layout';
import ProjectDetailSkeleton from '@/components/web/projects/ProjectDetailSkeleton';
import type { Client, Project, Image, MoreProject, Image } from '@/db/schema';

const ProjectDetail = () => {
  const params = useParams();
  const id = params.id as string;
  const [loading, setLoading] = useState(true);
  const [project, setProject] = useState<Project | null>(null);
  const [client, setClient] = useState<Client | null>(null);
  const [projects, setProjects] = useState<Project[]>([]);
  const [images, setImages] = useState<Image[]>([]);
  const [more, setMore] = useState<MoreProject[]>([]);
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);

  useEffect(() => {
    const fetchAll = async () => {
      try {
        setLoading(true);
        const [allProjects, singleProject,  getImages, getMore
          
        ] = await Promise.all([
          fetch('/api/projects'),
          fetch(`/api/projects/${id}`),
          fetch(`/api/images/${id}/project_id`),
          fetch(`/api/more-projects/${id}/project_id`),
        ]);

        const AllData: Project[] = await allProjects.json();
        setProjects(AllData);
        const data: Project = await singleProject.json();
        setProject(data);

      const response = await fetch(`/api/clients/${data?.clientId}`);
       
        const clientData: Client = await response.json();
        setClient(clientData);
        const imageData: Image = await getImages.json();
        setImages(imageData);
        const moreData: MoreProject = await getMore.json();
        setMore(moreData);
      } catch (error) {
        setProject(null);
        throw new Error(`Failed to fetch project data ${error}`);
      } finally {
        setLoading(false);
      }
    };

    

    fetchAll();
  }, [id]);

  if (loading) {
    return (
      <WebLayout>
        <ProjectDetailSkeleton />
      </WebLayout>
    );
  }

  if (!project) {
    return (
      <WebLayout>
        <div className="pt-32 pb-16 text-center">
          <h1 className="mb-6 font-bold text-3xl text-oki-gray-dark">
            Project Not Found
          </h1>
          <p className="mb-8 text-muted-foreground">
            The project you're looking for doesn't exist or has been moved.
          </p>
          <Link href="/projects">
            <Button className="bg-oki-blue-dark text-white hover:bg-oki-blue-light">
              View All Projects
            </Button>
          </Link>
        </div>
      </WebLayout>
    );
  }

  const relatedProjects = projects
    .filter((p) => p.category === project.category && p.id !== project.id)
    .slice(0, 2);

  const splitParagraphs = (text: string) => {
    return text.split('\r\n').filter((paragraph) => paragraph.trim() !== '');
  };

  const projectImages = images
    ? images.map((img) => ({
        src: img.url,
        alt: project.title,
      }))
    : [];

  return (
    <WebLayout>
   
        <section
          className=" py-20 text-white"
        style={{
          backgroundImage: `linear-gradient(to right, rgba(0, 70, 173, 0.85), rgba(0, 160, 233, 0.85)), url(${project.image})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
        }}
        >
          <div className="container px-4">
            <div className="max-w-3xl pt-12">
              <Link
                className="mb-4 inline-flex items-center text-white/90 hover:text-white"
                href="/projects"
              >
                <ArrowLeft className="mr-2" size={16} />
                <span>Back to Projects</span>
              </Link>
              <h1 className="mb-6 font-bold text-4xl md:text-5xl">
                {project.title}
              </h1>
            </div>
          </div>
        </section>

        {/* Project Details */}
        <section className="bg-white py-16">
          <div className="container px-4">
            <div className="grid grid-cols-1 gap-12 md:grid-cols-3">
              <div className="md:col-span-2">
                <h2 className="mb-4 font-bold text-3xl text-oki-gray-dark">
                  Project Overview
                </h2>
                <p className="mb-6 text-lg text-muted-foreground">
                  {project.description}
                </p>
                {project.doc && (
                  <div
                    className="prose prose-lg max-w-none text-oki-gray-dark"
                    dangerouslySetInnerHTML={{ __html: project.doc }}
                  />
                )}

                {more && more.length > 0 && (
                  <div className="mt-12">
                    <h3 className="mb-6 font-bold text-2xl text-oki-gray-dark">
                      More Project Details
                    </h3>
                    <div className="space-y-8">
                      {more.map((mp) => (
                        <div
                          key={mp.id}
                          className={cn(
                            'flex flex-col gap-6 md:flex-row',
                            mp.position === 'right' && 'md:flex-row-reverse'
                          )}
                        >
                          <div className="md:w-1/2">
                            {mp.image && (
                              <Image
                                alt="More Project Image"
                                className="h-auto w-full rounded-lg object-cover"
                                height={400}
                                src={mp.image}
                                width={600}
                              />
                            )}
                          </div>
                          <div className="md:w-1/2">
                            <div
                              className="prose prose-lg max-w-none text-oki-gray-dark"
                              dangerouslySetInnerHTML={{ __html: mp.doc }}
                            />
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {projectImages.length > 0 && (
                  <div className="mt-12">
                    <h3 className="mb-6 font-bold text-2xl text-oki-gray-dark">
                      Project Gallery
                    </h3>
                    <div className="grid grid-cols-2 gap-4 md:grid-cols-3">
                      {projectImages.map((img, index) => (
                        <div
                          key={index}
                          className="relative h-40 w-full cursor-pointer overflow-hidden rounded-lg"
                          onClick={() => setLightboxIndex(index)}
                        >
                          <Image
                            alt={img.alt || 'Project Image'}
                            className="h-full w-full object-cover transition-transform duration-300 hover:scale-105"
                            layout="fill"
                            src={img.src}
                          />
                        </div>
                      ))}
                    </div>
                    <Lightbox
                      captions={{ showToggle: true, descriptionMaxLines: 3 }}
                      close={() => setLightboxIndex(null)}
                      index={lightboxIndex || 0}
                      open={lightboxIndex !== null}
                      plugins={[Captions, Thumbnails]}
                      slides={projectImages}
                    />
                  </div>
                )}
              </div>

              <div className="md:col-span-1">
                <div className="rounded-lg bg-gray-100 p-6">
                  <h3 className="mb-4 font-bold text-2xl text-oki-gray-dark">
                    Project Information
                  </h3>
                  <ul className="space-y-3 text-oki-gray-dark">
                    {project.location && (
                      <li className="flex items-center">
                        <MapPin className="mr-2 h-5 w-5 text-oki-blue-dark" />
                        <span>Location: {project.location}</span>
                      </li>
                    )}
                    {project.complete && (
                      <li className="flex items-center">
                        <Calendar className="mr-2 h-5 w-5 text-oki-blue-dark" />
                        <span>Status: {project.complete}</span>
                      </li>
                    )}
                    {client?.name && (
                      <li className="flex  flex-col">
                        <span>Client: </span>
                        <Image src={client.image} alt={client.name} width={200} height={200} />
                        <span className='text-2xl font-bold'>{client.name}</span>
                      </li>
                    )} 
                    {project.link && (
                      <li className="flex items-center">
                        <span>
                          <Link
                            className="text-oki-blue-dark hover:underline"
                            href={project.link}
                            target="_blank"
                          >
                            View Project Link
                          </Link>
                        </span>
                      </li>
                    )}
                  </ul>
                </div>

                {relatedProjects.length > 0 && (
                  <div className="mt-12 rounded-lg bg-gray-100 p-6">
                    <h3 className="mb-4 font-bold text-2xl text-oki-gray-dark">
                      Related Projects
                    </h3>
                    <ul className="space-y-4">
                      {relatedProjects.map((rp) => (
                        <li key={rp.id}>
                          <Link
                            className="font-medium text-oki-blue-dark hover:underline"
                            href={`/projects/${rp.id}`}
                          >
                            {rp.title}
                          </Link>
                          <p className="text-sm text-muted-foreground">
                            {rp.description}
                          </p>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            </div>
          </div>
        </section>


        {/* Related Projects */}
                {relatedProjects.length > 0 && (
                  <section className="py-16 bg-oki-gray-light">
                    <div className="container mx-auto px-4">
                      <h2 className="text-3xl font-bold mb-10 text-center text-oki-gray-dark">
                        Related Projects
                      </h2>
        
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-8">
                        {relatedProjects.map((relatedProject) => (
                          <div
                            key={relatedProject.id}
                            className="group bg-white rounded-lg overflow-hidden shadow-md hover:shadow-xl transition-shadow"
                          >
                            <div className="h-64 overflow-hidden">
                              <img
                                src={relatedProject.image}
                                alt={relatedProject.title}
                                className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105"
                              />
                            </div>
                            <div className="p-6">
                              <div className="mb-3">
                                <span className="bg-oki-gray-light text-oki-gray-dark text-sm px-3 py-1 rounded-full capitalize">
                                  {relatedProject.category.replace("-", " ")}
                                </span>
                              </div>
                              <Link
                                to={`/projects/${relatedProject.id}`}
                                className="flex items-center text-oki-blue-dark font-medium hover:text-oki-blue-light transition-colors"
                              >
                                <h3 className="text-2xl font-semibold mb-3 text-oki-gray-dark">
                                  {relatedProject.title}
                                </h3>
                              </Link>
                              <Link
                                to={`/projects/${relatedProject.id}`}
                                className="flex items-center text-oki-blue-dark font-medium hover:text-oki-blue-light transition-colors"
                              >
                                <span>View Project</span>
                                <ArrowRight size={16} className="ml-2" />
                              </Link>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </section>
                )}

        {/* Call to Action */}
        <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>
      
    </WebLayout>
  );
};

export default ProjectDetail;
