import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import heroBg from "../assets/projects-hero.jpg";
import "../styles/Projects.css";

const Projects = () => {
  const [selectedSector, setSelectedSector] = useState("all");
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);
  const [expandedDescriptions, setExpandedDescriptions] = useState({});
  const [lightboxImage, setLightboxImage] = useState(null);

  const sectorRef = useRef(null);

  const sectors = [
    { label: "All", value: "all" },
    { label: "Water Supply", value: "water supply" },
    { label: "Storm Water", value: "storm water" },
    { label: "Electromechanical", value: "electromechanical & instrumentation" },
    { label: "Real Estate / Buildings", value: "real estate / buildings" },
    { label: "Tunnel", value: "tunnel" },
    { label: "Roads", value: "roads" },
    { label: "Wastewater / Sewerage", value: "wastewater / sewerage" },
    { label: "Irrigation", value: "irrigation" },
    { label: "Renewable Energy", value: "renewable energy" },
  ];

  useEffect(() => {
    const fetchProjects = async () => {
      try {
        const res = await axios.get(
          `${process.env.REACT_APP_API_BASE_URL}/api/projects`
        );
        setProjects(Array.isArray(res.data) ? res.data : []);
      } catch (err) {
        console.error("Error fetching projects:", err);
      } finally {
        setLoading(false);
      }
    };
    fetchProjects();
  }, []);

  useEffect(() => {
    if (window.location.hash === "#sectors" && sectorRef.current) {
      setTimeout(() => {
        sectorRef.current.scrollIntoView({ behavior: "smooth" });
      }, 200);
    }
  }, []);

  const filteredProjects = projects.filter((p) => {
    if (selectedSector === "all") return true;
    return (
      p.sector &&
      p.sector.toLowerCase().trim() === selectedSector.toLowerCase().trim()
    );
  });

  const toggleDescription = (id) => {
    setExpandedDescriptions((prev) => ({
      ...prev,
      [id]: !prev[id],
    }));
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Hero Section */}
      <div
        className="relative bg-cover bg-center h-[60vh] flex items-center justify-center"
        style={{ backgroundImage: `url(${heroBg})` }}
      >
        <div className="absolute inset-0 bg-black bg-opacity-50"></div>
        <div className="relative z-10 text-center px-4">
          <h1 className="text-3xl sm:text-4xl md:text-5xl font-extrabold text-white">
            Our Projects
          </h1>
          <p className="text-lg sm:text-xl md:text-2xl text-white mt-2 italic">
            Stronger Partnerships, Greater Success
          </p>
        </div>
      </div>

      {/* Sector Buttons */}
      <div
        ref={sectorRef}
        className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4 px-4 mt-8 mb-10"
      >
        {sectors.map((sector, index) => {
          const bgColors = [
            "bg-gradient-to-r from-blue-500 to-indigo-500",
            "bg-gradient-to-r from-green-400 to-green-600",
            "bg-gradient-to-r from-yellow-400 to-yellow-600",
            "bg-gradient-to-r from-pink-400 to-pink-600",
            "bg-gradient-to-r from-purple-400 to-purple-600",
            "bg-gradient-to-r from-red-400 to-red-600",
          ];
          const isSelected = selectedSector === sector.value;
          return (
            <button
              key={sector.value}
              onClick={() => setSelectedSector(sector.value)}
              className={`text-white font-semibold px-5 py-3 rounded-2xl shadow-lg transition-all duration-300 hover:scale-105
              ${bgColors[index % bgColors.length]}
              ${isSelected ? "ring-4 ring-white ring-offset-2" : ""}`}
            >
              {sector.label}
            </button>
          );
        })}
      </div>

      {/* Projects Grid */}
      <div className="px-6 mb-16 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-3 gap-6">
        {loading ? (
          <p className="text-center text-xl text-gray-500">Loading projects...</p>
        ) : filteredProjects.length === 0 ? (
          <p className="text-center text-xl text-gray-600">No projects available.</p>
        ) : (
          filteredProjects.map((project) => (
            <div key={project.id} className="radar-card bg-white rounded-xl shadow-lg overflow-hidden hover:shadow-2xl transition flex flex-col h-full">
              
              {project.image && (
                <div className="radar-image-container relative w-full aspect-[16/9] bg-gray-200 overflow-hidden flex-shrink-0">
                  <img
                    src={`${process.env.REACT_APP_API_BASE_URL}${project.image}`}
                    alt={project.name}
                    className="radar-image absolute inset-0 w-full h-full object-cover cursor-pointer"
                    onClick={(e) => {
                      e.stopPropagation();
                      setLightboxImage(`${process.env.REACT_APP_API_BASE_URL}${project.image}`);
                    }}
                  />
                </div>
              )}

              <div className="p-4 flex flex-col flex-grow">
                <h3 className="radar-title text-lg font-bold text-blue-800 leading-tight">
                  {project.name}
                </h3>
                <p className="text-sm text-gray-600 mt-1 font-semibold">
                Sector: {project.sector
                  .split(" ")
                  .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
                  .join(" ")}
              </p>



                {project.location && (
                  <p className="text-sm text-gray-600">
                    Location: {project.location}
                  </p>
                )}

                {project.description && (
                  <div className="text-sm text-gray-700 mt-auto pt-4">
                    <p>
                      {expandedDescriptions[project.id]
                        ? project.description
                        : project.description.slice(0, 100) + "..."}
                    </p>
                    {project.description.length > 100 && (
                      <button
                        onClick={() => toggleDescription(project.id)}
                        className="text-blue-600 underline text-sm mt-1"
                      >
                        {expandedDescriptions[project.id] ? "Read Less" : "Read More"}
                      </button>
                    )}
                  </div>
                )}
              </div>
            </div>
          ))
        )}
      </div>

      {/* Image Lightbox */}
      {lightboxImage && (
        <div
          className="fixed inset-0 bg-black bg-opacity-80 z-50 flex items-center justify-center"
          onClick={() => setLightboxImage(null)}
        >
          <div className="relative" onClick={(e) => e.stopPropagation()}>
            <button
              onClick={() => setLightboxImage(null)}
              className="absolute -top-4 -right-4 text-white text-3xl font-bold"
            >
              ×
            </button>
            <img src={lightboxImage} alt="Project" className="max-w-[90vw] max-h-[90vh] object-contain" />
          </div>
        </div>
      )}
    </div>
  );
};

export default Projects;
