"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { ChevronRight, LayoutGrid, X, Maximize2 } from "lucide-react";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import Navbar from "@/components/Navbar";
import Breadcrumbs from "@/components/Breadcrumbs";
import Footer from "@/components/Footer";
import { cn } from "@/lib/utils";

interface Project {
    id: number;
    title: string;
    location: string;
    type: string;
    specs: string;
    col: string;
    height: string;
    images: string[];
}

// Register GSAP plugins
if (typeof window !== "undefined") {
    gsap.registerPlugin(ScrollTrigger);
}

export default function ProjectsPage() {
    const mainRef = useRef<HTMLDivElement>(null);
    const [hoveredProject, setHoveredProject] = useState<number | null>(null);
    const [selectedProject, setSelectedProject] = useState<Project | null>(null);

    useEffect(() => {
        const ctx = gsap.context(() => {
            // Hero Animations
            const heroTl = gsap.timeline();
            heroTl.from(".project-hero-badge", { y: 20, opacity: 0, delay: 0.5 })
                .from(".project-hero-title", { y: 40, opacity: 0, duration: 1.2, stagger: 0.2 }, "-=0.6")
                .from(".project-hero-desc", { y: 20, opacity: 0, duration: 1 }, "-=0.8");

            // Reveal animations for sections
            gsap.utils.toArray<HTMLElement>(".reveal-up").forEach((elem) => {
                gsap.from(elem, {
                    y: 60,
                    opacity: 0,
                    duration: 1.2,
                    ease: "power3.out",
                    scrollTrigger: {
                        trigger: elem,
                        start: "top 85%",
                        toggleActions: "play none none none"
                    }
                });
            });
        }, mainRef);

        return () => ctx.revert();
    }, []);

    const projectsRaw = [
        { id: 1, title: "Modern Private Residence", location: "Colombo 07", type: "Luxury Residential", specs: "iRoof Max Autumn Red • 450sqm Installation", col: "xl:col-span-8", height: "h-[400px] xl:h-[600px]" },
        { id: 2, title: "Premium Residential Villa", location: "Kandy", type: "Boutique Stay", specs: "iRoof Max Brick Red • Thermal Insulation", col: "xl:col-span-4", height: "h-[400px] xl:h-[600px]" },
        { id: 3, title: "Brick House", location: "Biyagama", type: "Residential", specs: "iRoof Max Dark Green • Heavy Duty", col: "xl:col-span-4", height: "h-[400px] xl:h-[500px]" },
        { id: 4, title: "Coastal Private Villa", location: "Galle", type: "Resort", specs: "iRoof Max Chocolate Brown • Coastal Specs", col: "xl:col-span-4", height: "h-[400px] xl:h-[500px]" },
        { id: 5, title: "CityScape Builders ", location: "Kurunegala", type: "Commercial", specs: "iRoof Max Autumn Red • Multi-tiered", col: "xl:col-span-4", height: "h-[400px] xl:h-[500px]" },
        { id: 6, title: "Oakwood Residences", location: "Rajagiriya", type: "Residential", specs: "iRoof Max Brick Red • Modern Aesthetic", col: "xl:col-span-6", height: "h-[400px] xl:h-[550px]" },
        { id: 7, title: "Cornerstone Commercial", location: "Nuwara Eliya", type: "Commercial", specs: "iRoof Max Dark Green • Cold Climate", col: "xl:col-span-6", height: "h-[400px] xl:h-[550px]" },
    ];

    const curatedProjects = projectsRaw.map(p => ({
        ...p,
        images: [
            `/images/${p.id}.1.webp`,
            `/images/${p.id}.2.webp`,
            `/images/${p.id}.3.webp`,
            `/images/${p.id}.4.webp`
        ]
    }));

    const feedbacks = [
        "m7VS9ZB2Uo4", "9vYa7XHXm2o", "RVPvVvvNL2M", "D16EXdgzmow",
        "XWyMF4KN69U", "w2m_Rx11JjQ", "9r2A1rmIbyM", "s7I2YE8auhc"
    ];

    return (
        <main ref={mainRef} className="min-h-screen bg-white">
            <Navbar />

            {/* PROJECTS HERO - Banner */}
            <section className="relative pt-24 pb-8 md:pt-40 md:pb-16 min-h-[20vh] w-full flex items-center justify-center overflow-hidden mb-24">
                <Image
                    src="/images/pexels9.webp"
                    alt="Projects Background"
                    fill
                    className="object-cover"
                    priority
                />
                {/* Dark overlay for text readability */}
                <div className="absolute inset-0 bg-brand-dark/70" />

                <div className="relative z-10 text-center px-6 reveal-up">
                    <h1 className="project-hero-title text-4xl md:text-6xl lg:text-7xl font-medium text-white tracking-tight mt-6">
                        Our Projects
                    </h1>
                </div>
            </section>

            {/* PROJECTS SHOWCASE GRID - #case-studies */}
            <section id="case-studies" className="py-8 bg-white scroll-mt-20">
                <div className="max-w-[1400px] mx-auto px-8 md:px-16 lg:px-32 xl:px-40 pb-8 mt-4">
                    <Breadcrumbs items={[{ label: "Projects" }]} className="mb-8" />
                </div>
                <div className="max-w-[1400px] mx-auto px-8 md:px-16 lg:px-32 xl:px-40">
                    <div className="flex flex-col xl:flex-row xl:items-end justify-between gap-12 mb-20 reveal-up">
                        <div>
                            <div className="flex items-center gap-4 mb-4">
                                <div className="h-[1px] w-6 bg-brand-accent" />
                                <span className="text-[11px] font-medium text-brand-accent uppercase tracking-widest">Active Archives</span>
                            </div>
                            <h2 className="text-3xl md:text-[2.5rem] font-semibold text-brand-dark tracking-tight">Installation Gallery</h2>
                        </div>
                        <div className="flex items-center gap-8">
                            <div className="flex items-center gap-3 text-[10px] font-medium text-brand-dark/40 uppercase tracking-widest cursor-default">
                                <LayoutGrid size={14} className="text-brand-accent" />
                                <span>Grid View</span>
                            </div>
                            <div className="h-4 w-[1px] bg-zinc-200" />
                        </div>
                    </div>

                    {/* MASONRY STYLE GRID */}
                    <div className="grid grid-cols-1 xl:grid-cols-12 gap-6 reveal-up">
                        {curatedProjects.map((project, i) => (
                            <div
                                key={project.id}
                                className={cn(
                                    "group relative overflow-hidden bg-zinc-100 transition-all duration-1000 cursor-pointer border border-brand-dark/5 shadow-sm",
                                    project.col,
                                    project.height
                                )}
                                onMouseEnter={() => setHoveredProject(project.id)}
                                onMouseLeave={() => setHoveredProject(null)}
                                onClick={() => setSelectedProject(project)}
                            >
                                {/* Base Image (x.1) */}
                                <Image
                                    src={project.images[0]}
                                    alt={project.title}
                                    fill
                                    className={cn(
                                        "object-cover transition-all duration-1000",
                                        hoveredProject === project.id ? "opacity-0 scale-110" : "opacity-100 scale-100 grayscale-[0.2]"
                                    )}
                                />
                                {/* Hover Image (x.2) */}
                                <Image
                                    src={project.images[1]}
                                    alt={`${project.title} Detail`}
                                    fill
                                    className={cn(
                                        "object-cover transition-all duration-1000 absolute inset-0",
                                        hoveredProject === project.id ? "opacity-100 scale-100" : "opacity-0 scale-90"
                                    )}
                                />

                                {/* Project Overlay (Minimal) */}
                                <div className="absolute inset-0 bg-gradient-to-t from-brand-dark/90 via-brand-dark/20 to-transparent opacity-0 group-hover:opacity-100 transition-all duration-700 p-8 md:p-12 flex flex-col justify-end">
                                    <div className="relative z-10 transform translate-y-4 group-hover:translate-y-0 transition-transform duration-500">
                                        <p className="text-[10px] font-black text-brand-accent uppercase tracking-[0.4em] mb-4 flex items-center gap-3">
                                            <span className="w-6 h-[1px] bg-brand-accent" />
                                            Active Case 0{i + 1}
                                        </p>
                                        <h3 className="text-2xl md:text-4xl font-black text-white tracking-tighter mb-2 italic">{project.title}</h3>
                                        <p className="text-sm font-bold text-white/50 mb-8 uppercase tracking-widest">{project.location} • {project.type}</p>

                                        <div className="flex items-center gap-8 pt-8 border-t border-white/10">
                                            <div>
                                                <p className="text-[8px] font-black text-white/30 uppercase tracking-[0.2em] mb-1">Specifications</p>
                                                <p className="text-[10px] font-bold text-white italic">{project.specs}</p>
                                            </div>
                                            <button className="ml-auto w-12 h-12 md:w-14 md:h-14 rounded-full bg-brand-accent flex items-center justify-center text-white hover:bg-white hover:text-brand-dark transition-all duration-500 shadow-xl group/btn">
                                                <Maximize2 size={20} className="group-hover/btn:scale-110 transition-transform" />
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                {/* Floating Index */}
                                <div className="absolute top-10 right-10 text-6xl font-black text-white/10 group-hover:text-brand-accent/20 transition-colors pointer-events-none">
                                    0{i + 1}
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            </section>

            {/* TESTIMONIALS SECTION - #feedbacks */}
            <section id="feedbacks" className="py-24 bg-zinc-50 scroll-mt-20 overflow-hidden">
                <div className="max-w-[1400px] mx-auto px-8 md:px-16 lg:px-32 xl:px-40">
                    <div className="flex flex-col items-center text-center mb-20 reveal-up">
                        <div className="flex items-center gap-4 mb-4 group">
                            <div className="h-[1.5px] w-8 bg-brand-accent" />
                            <span className="text-[11px] font-medium text-brand-accent uppercase tracking-[0.4em]">Testimonials</span>
                            <div className="h-[1.5px] w-8 bg-brand-accent" />
                        </div>
                        <h2 className="text-3xl md:text-[2.5rem] font-semibold text-brand-dark tracking-tighter mb-6">
                            Verified <span className="text-brand-accent">Customer</span> Feedback
                        </h2>
                        <p className="text-brand-dark/40 text-sm md:text-base font-medium max-w-2xl leading-relaxed">
                            Watch what our clients have to say about their experience with iRoof advanced roofing solutions across the island.
                        </p>
                    </div>

                    {/* YouTube Video Grid - No Custom Thumbnail */}
                    <div className="grid grid-cols-1 xl:grid-cols-4 gap-6 md:gap-8 reveal-up px-0">
                        {feedbacks.map((videoId, idx) => (
                            <div key={idx} className="group relative aspect-video bg-black overflow-hidden shadow-sm hover:shadow-xl transition-all duration-500 border border-brand-dark/10">
                                <iframe
                                    className="absolute inset-0 w-full h-full z-10"
                                    src={`https://www.youtube.com/embed/${videoId}?rel=0&vq=hd720`}
                                    title={`Customer Feedback ${idx + 1}`}
                                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                    allowFullScreen
                                ></iframe>
                            </div>
                        ))}
                    </div>
                </div>
            </section>

            {/* PROJECT GALLERY MODAL */}
            {selectedProject && (
                <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 md:p-10">
                    <div className="absolute inset-0 bg-brand-dark/95 backdrop-blur-xl animate-in fade-in duration-500" onClick={() => setSelectedProject(null)} />

                    <div className="relative w-full max-w-7xl h-full flex flex-col gap-6 md:gap-10 animate-in zoom-in-95 duration-500 overflow-y-auto custom-scrollbar pt-20 pb-10">
                        {/* Header */}
                        <div className="flex items-center justify-between text-white shrink-0">
                            <div>
                                <h2 className="text-3xl md:text-5xl font-black tracking-tighter mb-2">{selectedProject.title}</h2>
                                <p className="text-xs md:text-sm text-brand-accent font-bold uppercase tracking-[0.3em]">{selectedProject.location}</p>
                            </div>
                            <button
                                onClick={() => setSelectedProject(null)}
                                className="w-12 h-12 md:w-16 md:h-16 rounded-full border border-white/10 flex items-center justify-center hover:bg-white hover:text-black transition-all group"
                            >
                                <X className="w-6 h-6 md:w-8 md:h-8 group-hover:rotate-90 transition-transform" />
                            </button>
                        </div>

                        {/* Image Grid - Show 4 images */}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-8 flex-1">
                            {selectedProject.images.map((img: string, idx: number) => (
                                <div key={idx} className="relative aspect-video overflow-hidden group/img bg-white/5 border border-white/10 shadow-sm">
                                    <Image
                                        src={img}
                                        alt={`${selectedProject.title} - Image ${idx + 1}`}
                                        fill
                                        className="object-cover group-hover/img:scale-105 transition-transform duration-1000"
                                    />
                                </div>
                            ))}
                        </div>

                        {/* Footer Info */}
                        <div className="flex flex-col md:flex-row items-center justify-between gap-6 pt-10 border-t border-white/10">
                            <p className="text-white/40 text-sm font-medium italic max-w-md text-center md:text-left">
                                This project showcases our commitment to durability and architectural aesthetics using premium iRoof materials.
                            </p>
                            <Link
                                href="/contact#quotation"
                                className="bg-brand-accent text-white px-10 py-5 rounded-full text-[10px] font-black uppercase tracking-[0.3em] hover:bg-white hover:text-brand-dark transition-all duration-500 shadow-2xl"
                                onClick={() => setSelectedProject(null)}
                            >
                                GET QUOTE FOR THIS DESIGN
                            </Link>
                        </div>
                    </div>
                </div>
            )}

            {/* CALL TO ACTION */}
            {/* <section className="py-32 bg-white border-t border-brand-dark/5 pt-24 pb-32">
                <div className="max-w-[1400px] mx-auto px-8 md:px-16 lg:px-32 xl:px-40 text-center reveal-up">
                    <div className="flex items-center justify-center gap-4 mb-4">
                        <div className="h-[1.5px] w-8 bg-brand-accent" />
                        <span className="text-[11px] font-black text-brand-accent uppercase tracking-[0.4em]">Inquiry Protocol</span>
                        <div className="h-[1.5px] w-8 bg-brand-accent" />
                    </div>
                    <h2 className="text-3xl md:text-[2.5rem] font-black text-brand-dark tracking-tighter leading-none mb-12">
                        Start Your Own <br />
                        <span className="italic font-black text-brand-dark/10 text-[4rem] md:text-[6rem]">Arch-Liaison</span>
                    </h2>
                    <Link
                        href="/contact"
                        className="inline-flex items-center gap-6 bg-brand-dark text-white px-12 py-6 rounded-full text-xs font-black uppercase tracking-[0.3em] hover:bg-brand-accent transition-all duration-700 shadow-2xl hover:shadow-brand-accent/20"
                    >
                        Consult Our Engineers <ChevronRight size={16} />
                    </Link>
                </div>
            </section> */}

            <Footer />
        </main>
    );
}
