"use client";
import DOMPurify from "isomorphic-dompurify";
import Image from "next/image";
import { useMemo, useState } from "react";
import Lightbox from "yet-another-react-lightbox";
import Fullscreen from "yet-another-react-lightbox/plugins/fullscreen";
import Thumbnails from "yet-another-react-lightbox/plugins/thumbnails";
import Zoom from "yet-another-react-lightbox/plugins/zoom";
import type { Project } from "@/types/models";

export default function ProjectDetailsClient({ project }: { project: Project }) {
  const [isGalleryOpen, setIsGalleryOpen] = useState(false);
  const [currentIndex, setCurrentIndex] = useState(0);

  const coverImageUrl = project.coverImage?.replace("/uploads/", "/api/uploads/") || "/images/placeholder.webp";

  // Sanitize the description HTML to prevent XSS
  const sanitizedDescription = useMemo(
    () => DOMPurify.sanitize(project.description),
    [project.description],
  );

  const galleryItems = [
    { original: coverImageUrl, thumbnail: coverImageUrl },
    ...project.galleryImages.map((image) => ({
      original: image.replace("/uploads/", "/api/uploads/"),
      thumbnail: image.replace("/uploads/", "/api/uploads/"),
    })),
  ];

  const slides = galleryItems.map((item) => ({ src: item.original }));

  const handleImageClick = (index: number) => {
    setCurrentIndex(index);
    setIsGalleryOpen(true);
  };

  // Lightbox handles keyboard navigation and touch gestures out of the box

  return (
    <section className="min-h-screen bg-[#030f18] pb-24 relative overflow-hidden">
      {/* Gradient border that fades from left to right */}
      <div className="absolute top-0 left-0 w-[85%] h-[1px] bg-gradient-to-r from-[#B87333] to-transparent" />

      {/* Floating Elements */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none z-0">
        <div className="absolute top-1/4 left-1/4 w-64 h-64 bg-[#B87333]/10 rounded-full blur-3xl animate-float"></div>
        <div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-[#B87333]/10 rounded-full blur-3xl animate-float-delayed"></div>
      </div>

      {/* Hero Section */}
      <div className="relative h-[60vh] w-full flex items-center justify-center overflow-hidden mb-16">
        <div className="absolute inset-0">
          <Image
            src={coverImageUrl}
            alt={project.name}
            fill
            className="object-cover object-center"
            quality={90}
            priority
          />
        </div>
        <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent" />
        <div className="relative z-20 text-center">
          <h1 className="text-4xl md:text-5xl font-bold text-white drop-shadow-lg mb-8">{project.name}</h1>
          <a
            href="/projects"
            className="inline-flex items-center px-8 py-3 rounded-full bg-[#B87333] text-white font-semibold shadow-lg hover:bg-[#A05A2C] hover:scale-105 transition-all focus:outline-none focus:ring-2 focus:ring-[#B87333] focus:ring-offset-2 focus:ring-offset-black/50"
          >
            <svg
              className="w-5 h-5 mr-2 transform group-hover:-translate-x-1 transition-transform"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M7 16l-4-4m0 0l4-4m-4 4h18"
              />
            </svg>
            Back to Projects
          </a>
        </div>
        {/* Gradient border at the bottom */}
        <div className="absolute bottom-0 right-0 w-[85%] h-[1px] bg-gradient-to-l from-[#B87333] to-transparent" />
      </div>

      {/* Description Card */}
      <div className="container mx-auto px-4 mb-12">
        <div className="max-w-3xl mx-auto bg-[#020c13] rounded-md border border-[#B87333]/30 shadow-md p-8 text-white text-lg leading-relaxed">
          <div dangerouslySetInnerHTML={{ __html: sanitizedDescription }} />
        </div>
      </div>

      {/* Gallery Section */}
      <div className="container mx-auto px-4">
        <h2 className="text-2xl font-bold text-white mb-6 text-center">Gallery</h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6">
          {galleryItems.map((item, idx) => (
            <button
              key={idx}
              type="button"
              className="group relative cursor-pointer bg-[#020c13] rounded-md border border-[#B87333]/30 shadow-md overflow-hidden transition-all duration-300 hover:scale-105 hover:shadow-lg focus:outline-none focus:ring-2 focus:ring-[#B87333] focus:ring-offset-2 focus:ring-offset-[#030f18]"
              onClick={() => handleImageClick(idx)}
              aria-label={`View image ${idx + 1} fullscreen`}
            >
              <div className="aspect-[4/3] relative">
                <Image
                  src={item.original}
                  alt={`Gallery image ${idx + 1} for ${project.name}`}
                  fill
                  className="object-cover"
                  quality={85}
                />
              </div>
              <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-all duration-300 rounded-md flex items-center justify-center">
                <div className="bg-white/20 backdrop-blur-sm rounded-full p-4 transform scale-75 group-hover:scale-100 transition-transform duration-300">
                  <svg className="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v6m4-3H6"
                    />
                  </svg>
                </div>
              </div>
            </button>
          ))}
        </div>
      </div>

      <Lightbox
        open={isGalleryOpen}
        close={() => setIsGalleryOpen(false)}
        index={currentIndex}
        slides={slides}
        plugins={[Thumbnails, Fullscreen, Zoom]}
      />
    </section>
  );
}
