"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Zap, Route, Building2, Droplets, Map, ArrowUpRight, CheckCircle, ShieldCheck } from "lucide-react";
import { SectionHeading } from "./section-heading";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";

type ProjectItem = {
  id: string;
  title: string;
  category: "Energy" | "Transport" | "Buildings" | "Water" | "Survey";
  categoryLabel: string;
  location: string;
  metric: string;
  image: string;
  description: string;
  highlights: string[];
  deliverables: string[];
  icon: typeof Zap;
};

const PROJECTS: ProjectItem[] = [
  {
    id: "proj-1",
    title: "Mountain Hydropower Substation & Civil Structures",
    category: "Energy",
    categoryLabel: "Energy & Hydropower",
    location: "Gandaki Province, Nepal",
    metric: "25 MW Power Capacity",
    image: "/images/sector-energy.jpg",
    description:
      "Turnkey civil construction and foundation engineering for high-head hydropower penstock support, transformer pads, and 33kV substation towers in rugged Himalayan mountain terrain.",
    highlights: [
      "Heavy RCC foundation works with slope stabilization",
      "Substation tower erection & high-tension cable conduits",
      "Environmental impact mitigation & erosion control",
    ],
    deliverables: ["Civil Foundation", "Transmission Towers", "EIA Compliance Report"],
    icon: Zap,
  },
  {
    id: "proj-2",
    title: "Mountain Highway Bituminous Paving & Slope Protection",
    category: "Transport",
    categoryLabel: "Roads & Transport",
    location: "Bagmati Province, Nepal",
    metric: "18.5 Km Highway Reach",
    image: "/images/sector-roads.jpg",
    description:
      "Comprehensive highway widening, gabion retaining wall construction, drainage culverts, and heavy-duty bituminous carpet paving designed for heavy vehicle transit.",
    highlights: [
      "Deep excavation and rock anchoring",
      "Pre-cast concrete drainage channels",
      "Quality-tested asphaltic concrete surfacing",
    ],
    deliverables: ["Bituminous Pavement", "Gabion Retaining Walls", "Culverts & Drainage"],
    icon: Route,
  },
  {
    id: "proj-3",
    title: "Multi-Story Commercial & Administrative Complex",
    category: "Buildings",
    categoryLabel: "Buildings & Urban",
    location: "Kathmandu Valley, Nepal",
    metric: "8-Story RCC Structure",
    image: "/images/sector-buildings.jpg",
    description:
      "Complete structural civil engineering, seismic-resistant RCC framework, interior partition layout, and HVAC/electrical system integration for an administrative facility.",
    highlights: [
      "Seismic-isolated foundation and shear wall engineering",
      "High-efficiency HVAC and electrical network installation",
      "Premium architectural finishing & glass facade integration",
    ],
    deliverables: ["RCC Framework", "HVAC & Electrical", "Turnkey Finishing"],
    icon: Building2,
  },
  {
    id: "proj-4",
    title: "District Drinking Water Treatment & Network",
    category: "Water",
    categoryLabel: "Water & Utilities",
    location: "Lumbini Province, Nepal",
    metric: "12,000 Liters/Hr WTP",
    image: "/images/sector-water.jpg",
    description:
      "Design-build implementation of raw water intake structures, rapid sand filtration treatment plant, overhead distribution tanks, and household feeder piping.",
    highlights: [
      "Intake weir construction on torrential river channel",
      "Sedimentation basin & chemical dosing automation",
      "High-density polyethylene (HDPE) distribution mainlines",
    ],
    deliverables: ["Intake Structure", "Water Treatment Plant", "Feeder Pipeline Network"],
    icon: Droplets,
  },
  {
    id: "proj-5",
    title: "Topographic & Spatial GIS Survey for Infrastructure",
    category: "Survey",
    categoryLabel: "Survey & GIS",
    location: "Karnali Province, Nepal",
    metric: "450 Hectares Mapped",
    image: "/images/about.jpg",
    description:
      "High-precision RTK GPS survey, 3D digital elevation modeling (DEM), and Geographic Information System mapping for regional infrastructure corridor planning.",
    highlights: [
      "Centimeter-accuracy DGPS contour surveying",
      "Satellite remote sensing & land use classification",
      "Comprehensive GIS database integration for municipal planning",
    ],
    deliverables: ["3D Contour Maps", "CAD Alignment Files", "GIS Spatial Database"],
    icon: Map,
  },
];

const CATEGORIES = [
  { key: "All", label: "All Projects" },
  { key: "Energy", label: "Energy & Power" },
  { key: "Transport", label: "Roads & Bridges" },
  { key: "Buildings", label: "Buildings & Urban" },
  { key: "Water", label: "Water Infrastructure" },
  { key: "Survey", label: "Survey & GIS" },
];

export function PortfolioShowcase() {
  const [activeCategory, setActiveCategory] = useState<string>("All");
  const [selectedProject, setSelectedProject] = useState<ProjectItem | null>(null);

  const filteredProjects =
    activeCategory === "All"
      ? PROJECTS
      : PROJECTS.filter((p) => p.category === activeCategory);

  return (
    <section id="portfolio" className="section-pad bg-background">
      <div className="mx-auto max-w-7xl px-4 md:px-6">
        <SectionHeading
          eyebrow="Landmark Capabilities"
          title="Engineering projects built to endure"
          description="A showcase of representative engineering capabilities across Nepal's core infrastructure sectors — delivered with precision, safety, and regulatory compliance."
        />

        {/* Category Filters */}
        <div className="mt-10 flex flex-wrap items-center justify-center gap-2">
          {CATEGORIES.map((cat) => {
            const active = activeCategory === cat.key;
            return (
              <button
                key={cat.key}
                onClick={() => setActiveCategory(cat.key)}
                className={`rounded-full px-5 py-2 text-xs font-semibold tracking-wide transition-all duration-300 ${
                  active
                    ? "bg-primary text-primary-foreground shadow-md shadow-primary/25"
                    : "bg-muted/70 text-muted-foreground hover:bg-muted hover:text-foreground"
                }`}
              >
                {cat.label}
              </button>
            );
          })}
        </div>

        {/* Project Grid */}
        <motion.div layout className="mt-12 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
          <AnimatePresence mode="popLayout">
            {filteredProjects.map((project) => {
              const Icon = project.icon;
              return (
                <motion.div
                  key={project.id}
                  layout
                  initial={{ opacity: 0, scale: 0.95 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.95 }}
                  transition={{ duration: 0.35 }}
                  className="group relative flex flex-col overflow-hidden rounded-xl border border-border bg-card transition-all duration-300 hover:border-primary/50 hover:shadow-xl hover:shadow-primary/5"
                >
                  {/* Image Container */}
                  <div className="relative aspect-[16/10] w-full overflow-hidden bg-muted">
                    <img
                      src={project.image}
                      alt={project.title}
                      className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-stone-950/80 via-stone-950/20 to-transparent" />
                    
                    {/* Badge */}
                    <div className="absolute top-3 left-3 flex items-center gap-1.5 rounded-md bg-stone-950/80 px-2.5 py-1 text-[11px] font-semibold text-white backdrop-blur-md">
                      <Icon className="h-3.5 w-3.5 text-amber-400" />
                      {project.categoryLabel}
                    </div>

                    {/* Metric pill */}
                    <div className="absolute bottom-3 left-3 rounded-md bg-primary/90 px-2.5 py-1 text-[11px] font-bold text-primary-foreground shadow-sm">
                      {project.metric}
                    </div>
                  </div>

                  {/* Body */}
                  <div className="flex flex-1 flex-col p-6">
                    <div className="text-xs font-medium text-muted-foreground">
                      {project.location}
                    </div>
                    <h3 className="mt-2 text-lg font-bold text-foreground group-hover:text-primary transition-colors">
                      {project.title}
                    </h3>
                    <p className="mt-2 text-xs leading-relaxed text-muted-foreground line-clamp-3">
                      {project.description}
                    </p>

                    <div className="mt-6 pt-4 border-t border-border flex items-center justify-between">
                      <span className="text-[11px] font-semibold text-primary uppercase tracking-wider">
                        BECS Standard Scope
                      </span>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setSelectedProject(project)}
                        className="h-8 px-3 text-xs font-medium hover:bg-primary/10 hover:text-primary"
                      >
                        View Details
                        <ArrowUpRight className="ml-1 h-3.5 w-3.5" />
                      </Button>
                    </div>
                  </div>
                </motion.div>
              );
            })}
          </AnimatePresence>
        </motion.div>

        {/* Modal Popup for Details */}
        <Dialog open={!!selectedProject} onOpenChange={() => setSelectedProject(null)}>
          {selectedProject && (
            <DialogContent className="max-w-2xl overflow-hidden p-0 sm:rounded-xl">
              <div className="relative aspect-video w-full overflow-hidden bg-muted">
                <img
                  src={selectedProject.image}
                  alt={selectedProject.title}
                  className="h-full w-full object-cover"
                />
                <div className="absolute inset-0 bg-gradient-to-t from-stone-950/90 via-stone-950/40 to-transparent" />
                <div className="absolute bottom-4 left-6 right-6">
                  <span className="inline-flex items-center gap-1.5 rounded bg-amber-400 px-2.5 py-0.5 text-xs font-bold text-stone-950">
                    {selectedProject.categoryLabel}
                  </span>
                  <DialogTitle className="mt-2 text-xl font-extrabold text-white sm:text-2xl">
                    {selectedProject.title}
                  </DialogTitle>
                  <DialogDescription className="text-xs text-stone-300">
                    {selectedProject.location} · {selectedProject.metric}
                  </DialogDescription>
                </div>
              </div>

              <div className="p-6 space-y-5">
                <div>
                  <h4 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                    Project Overview
                  </h4>
                  <p className="mt-1.5 text-sm leading-relaxed text-foreground">
                    {selectedProject.description}
                  </p>
                </div>

                <div>
                  <h4 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                    Engineering Highlights & Challenges Addressed
                  </h4>
                  <ul className="mt-2.5 space-y-2">
                    {selectedProject.highlights.map((h) => (
                      <li key={h} className="flex items-start gap-2.5 text-xs text-foreground">
                        <ShieldCheck className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
                        <span>{h}</span>
                      </li>
                    ))}
                  </ul>
                </div>

                <div>
                  <h4 className="text-xs font-bold uppercase tracking-wider text-muted-foreground">
                    Core Deliverables Handed Over
                  </h4>
                  <div className="mt-2.5 flex flex-wrap gap-2">
                    {selectedProject.deliverables.map((d) => (
                      <span
                        key={d}
                        className="inline-flex items-center gap-1.5 rounded-md border border-border bg-muted/50 px-3 py-1 text-xs font-medium text-foreground"
                      >
                        <CheckCircle className="h-3.5 w-3.5 text-primary" />
                        {d}
                      </span>
                    ))}
                  </div>
                </div>

                <div className="pt-4 border-t border-border flex items-center justify-between">
                  <div className="text-xs text-muted-foreground">
                    Registered under Companies Act, 2006 · BECS Pvt. Ltd.
                  </div>
                  <Button asChild size="sm">
                    <a href="#contact" onClick={() => setSelectedProject(null)}>
                      Inquire Similar Project
                    </a>
                  </Button>
                </div>
              </div>
            </DialogContent>
          )}
        </Dialog>
      </div>
    </section>
  );
}
