"use client";

import { useState, useMemo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { MagnifyingGlass, X, MapPin, Lightning, ShieldCheck } from "@phosphor-icons/react";
import { AnimatedSection, AnimatedItem } from "@/components/ui/AnimatedSection";
import EyebrowBadge from "@/components/ui/EyebrowBadge";

type Project = {
  id: string;
  title: string;
  category: "residential" | "commercial" | "microgrid";
  city: string;
  capacityKw: number;
  annualYieldKwh: string;
  billCutPct: number;
  image: string;
  description: string;
};

const PROJECTS: Project[] = [
  {
    id: "p1",
    title: "Indiranagar Solar Villa",
    category: "residential",
    city: "Bengaluru, KA",
    capacityKw: 8.5,
    annualYieldKwh: "12,400",
    billCutPct: 92,
    image: "/images/house-wide.jpg",
    description: "N-type TOPCon 24-panel array mounted on flat RCC roof with net-metering export feed and smart microinverter monitoring.",
  },
  {
    id: "p2",
    title: "EcoTech Tech Park Array",
    category: "commercial",
    city: "Hyderabad, TS",
    capacityKw: 120,
    annualYieldKwh: "175,000",
    billCutPct: 84,
    image: "/images/projects/hero.jpg",
    description: "Commercial rooftop install powering 4 floors of office space with automated cloud inverter telemetry and zero downtime.",
  },
  {
    id: "p3",
    title: "GreenValley Resort Grid",
    category: "microgrid",
    city: "Waynad, KL",
    capacityKw: 45,
    annualYieldKwh: "68,000",
    billCutPct: 95,
    image: "/images/services/services-bg.jpg",
    description: "Hybrid solar + battery storage solution powering off-grid eco-resort cabins during monsoon grid blackouts.",
  },
  {
    id: "p4",
    title: "Jayanagar Heritage Estate",
    category: "residential",
    city: "Bengaluru, KA",
    capacityKw: 5.2,
    annualYieldKwh: "7,800",
    billCutPct: 88,
    image: "/images/house-dusk.jpg",
    description: "Custom sloping tile roof installation with zero tile breakage statutory setbacks clear.",
  },
  {
    id: "p5",
    title: "Apex Logistics Hub",
    category: "commercial",
    city: "Chennai, TN",
    capacityKw: 250,
    annualYieldKwh: "360,000",
    billCutPct: 89,
    image: "/images/process/bg.jpg",
    description: "Industrial metal seam roof mount with PM Surya Ghar incentive approval and automated cleaning robots.",
  },
  {
    id: "p6",
    title: "Hilltop Community Microgrid",
    category: "microgrid",
    city: "Coorg, KA",
    capacityKw: 60,
    annualYieldKwh: "88,000",
    billCutPct: 96,
    image: "/images/savings/bg.jpg",
    description: "Shared community solar array distributing solar energy credits across 14 remote homestays.",
  },
];

export default function ProjectsGallery() {
  const [activeCategory, setActiveCategory] = useState<string>("all");
  const [searchQuery, setSearchQuery] = useState<string>("");
  const [selectedProject, setSelectedProject] = useState<Project | null>(null);

  const filteredProjects = useMemo(() => {
    return PROJECTS.filter((p) => {
      const matchesCategory = activeCategory === "all" || p.category === activeCategory;
      const matchesSearch =
        p.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        p.city.toLowerCase().includes(searchQuery.toLowerCase()) ||
        p.capacityKw.toString().includes(searchQuery);
      return matchesCategory && matchesSearch;
    });
  }, [activeCategory, searchQuery]);

  return (
    <section className="relative z-10 overflow-hidden bg-zinc-950 px-6 py-24 md:px-8 md:py-32">
      <AnimatedSection className="mx-auto max-w-[1400px]">
        {/* Header */}
        <div className="mb-12 flex flex-col items-center text-center">
          <AnimatedItem>
            <EyebrowBadge tone="dark" className="mb-4">
              Real Installations
            </EyebrowBadge>
          </AnimatedItem>
          <AnimatedItem>
            <h2 className="text-3xl font-semibold tracking-tight text-white md:text-5xl">
              Engineered Solar Showcase
            </h2>
          </AnimatedItem>
          <AnimatedItem>
            <p className="mt-4 max-w-[600px] text-sm text-zinc-400 md:text-base">
              Explore live installations across residential roofs, commercial parks, and rural microgrids.
            </p>
          </AnimatedItem>
        </div>

        {/* Filter Controls Bar */}
        <div className="mb-10 flex flex-col items-center justify-between gap-4 md:flex-row">
          {/* Category Tabs */}
          <div className="flex flex-wrap gap-2 rounded-2xl border border-white/10 bg-zinc-900/80 p-1.5 backdrop-blur-md">
            {[
              { id: "all", label: "All Projects" },
              { id: "residential", label: "Residential" },
              { id: "commercial", label: "Commercial" },
              { id: "microgrid", label: "Microgrids" },
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveCategory(tab.id)}
                className={`rounded-xl px-4 py-2 text-xs font-bold transition-all duration-300 ${
                  activeCategory === tab.id
                    ? "bg-amber-500 text-zinc-950 shadow-[0_0_15px_rgba(245,158,11,0.5)]"
                    : "text-zinc-400 hover:text-white"
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>

          {/* Search Input */}
          <div className="relative w-full max-w-xs">
            <MagnifyingGlass size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-zinc-400" />
            <input
              type="text"
              placeholder="Search by city, title or kW..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full rounded-2xl border border-white/10 bg-zinc-900/80 pl-10 pr-4 py-2.5 text-xs text-white placeholder-zinc-500 focus:border-amber-400 focus:outline-none"
            />
          </div>
        </div>

        {/* Gallery Grid */}
        <motion.div layout className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3">
          <AnimatePresence>
            {filteredProjects.map((project) => (
              <motion.div
                key={project.id}
                layout
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.9 }}
                transition={{ duration: 0.3 }}
                onClick={() => setSelectedProject(project)}
                className="group relative cursor-pointer overflow-hidden rounded-3xl border border-white/10 bg-zinc-900/80 shadow-xl transition-all duration-300 hover:-translate-y-1.5 hover:border-amber-400/50 hover:shadow-[0_10px_30px_rgba(245,158,11,0.25)]"
              >
                <div className="h-56 w-full overflow-hidden">
                  <img
                    src={project.image}
                    alt={project.title}
                    className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
                  />
                </div>
                <div className="p-6">
                  <div className="flex items-center justify-between text-xs text-amber-400">
                    <span className="font-mono font-bold uppercase tracking-wider">{project.category}</span>
                    <span className="flex items-center gap-1 text-zinc-400">
                      <MapPin size={14} />
                      {project.city}
                    </span>
                  </div>
                  <h3 className="mt-2 text-lg font-bold text-white group-hover:text-amber-300">{project.title}</h3>
                  <div className="mt-4 flex items-center justify-between border-t border-white/10 pt-4 text-xs">
                    <div>
                      <span className="text-zinc-500">System:</span>
                      <span className="ml-1 font-mono font-bold text-white">{project.capacityKw} kW</span>
                    </div>
                    <div>
                      <span className="text-zinc-500">Bill Cut:</span>
                      <span className="ml-1 font-mono font-bold text-emerald-400">-{project.billCutPct}%</span>
                    </div>
                  </div>
                </div>
              </motion.div>
            ))}
          </AnimatePresence>
        </motion.div>

        {/* Modal Lightbox */}
        <AnimatePresence>
          {selectedProject && (
            <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                onClick={() => setSelectedProject(null)}
                className="fixed inset-0 bg-black/80 backdrop-blur-md"
              />
              <motion.div
                initial={{ opacity: 0, scale: 0.95, y: 20 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.95, y: 20 }}
                className="relative z-10 w-full max-w-2xl overflow-hidden rounded-3xl border border-white/20 bg-zinc-950 p-6 text-white shadow-2xl"
              >
                <button
                  onClick={() => setSelectedProject(null)}
                  className="absolute right-4 top-4 z-20 rounded-full bg-black/60 p-2 text-white hover:bg-black"
                >
                  <X size={20} />
                </button>
                <div className="h-64 w-full overflow-hidden rounded-2xl">
                  <img src={selectedProject.image} alt={selectedProject.title} className="h-full w-full object-cover" />
                </div>
                <div className="mt-6">
                  <div className="flex items-center gap-2 text-xs font-bold text-amber-400 uppercase">
                    <Lightning size={16} weight="fill" />
                    <span>{selectedProject.category} Case Study</span>
                  </div>
                  <h3 className="mt-1 text-2xl font-bold text-white">{selectedProject.title}</h3>
                  <p className="mt-2 text-xs text-zinc-400 leading-relaxed">{selectedProject.description}</p>

                  <div className="mt-6 grid grid-cols-3 gap-3 rounded-2xl border border-amber-400/30 bg-amber-500/10 p-4 text-center">
                    <div>
                      <span className="text-[10px] text-zinc-400 uppercase">Capacity</span>
                      <div className="font-mono text-base font-bold text-white">{selectedProject.capacityKw} kW</div>
                    </div>
                    <div>
                      <span className="text-[10px] text-zinc-400 uppercase">Annual Yield</span>
                      <div className="font-mono text-base font-bold text-amber-300">{selectedProject.annualYieldKwh} kWh</div>
                    </div>
                    <div>
                      <span className="text-[10px] text-zinc-400 uppercase">Bill Cut</span>
                      <div className="font-mono text-base font-bold text-emerald-400">-{selectedProject.billCutPct}%</div>
                    </div>
                  </div>
                </div>
              </motion.div>
            </div>
          )}
        </AnimatePresence>
      </AnimatedSection>
    </section>
  );
}
