import { Link } from "@tanstack/react-router";
import { ArrowUpRight, ChevronLeft, ChevronRight, Expand, X } from "lucide-react";
import { useEffect, useState } from "react";
import {
  GALLERY_CATEGORIES,
  PORTFOLIO_ITEMS,
  type GalleryCategory,
  type PortfolioConcept,
} from "@/data/site";

interface PortfolioGalleryProps {
  compact?: boolean;
}

export function PortfolioGallery({ compact = false }: PortfolioGalleryProps) {
  const [activeCategory, setActiveCategory] = useState<GalleryCategory>("All");
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);

  const filtered =
    activeCategory === "All"
      ? PORTFOLIO_ITEMS
      : PORTFOLIO_ITEMS.filter((item) => item.category === activeCategory);

  const visibleItems: PortfolioConcept[] = compact ? filtered.slice(0, 6) : filtered;

  useEffect(() => {
    if (lightboxIndex === null) return;
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") setLightboxIndex(null);
      if (e.key === "ArrowRight") {
        setLightboxIndex((i) => (i === null ? null : (i + 1) % visibleItems.length));
      }
      if (e.key === "ArrowLeft") {
        setLightboxIndex((i) =>
          i === null ? null : (i - 1 + visibleItems.length) % visibleItems.length,
        );
      }
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [lightboxIndex, visibleItems.length]);

  const activeLightboxItem =
    lightboxIndex !== null ? visibleItems[lightboxIndex] : undefined;

  return (
    <div>
      <div
        className="flex flex-wrap gap-2"
        role="tablist"
        aria-label="Filter projects by room category"
      >
        {GALLERY_CATEGORIES.map((category) => {
          const selected = activeCategory === category;
          return (
            <button
              key={category}
              type="button"
              role="tab"
              aria-selected={selected}
              onClick={() => {
                setActiveCategory(category);
                setLightboxIndex(null);
              }}
              className={`rounded-sm px-4 py-2 text-xs font-medium tracking-wider uppercase transition-colors ${
                selected
                  ? "bg-charcoal text-charcoal-foreground"
                  : "border border-border bg-card text-foreground/80 hover:border-bronze hover:text-charcoal"
              }`}
            >
              {category}
            </button>
          );
        })}
      </div>

      <p className="mt-4 text-xs text-muted-foreground">
        Architectural design concepts illustrating remodeling styles across each room category.
      </p>

      <div className="mt-8 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
        {visibleItems.map((item, idx) => (
          <article
            key={item.slug}
            className="group overflow-hidden border border-border/80 bg-card transition-all duration-300 hover:border-bronze/60"
          >
            <div className="relative aspect-[4/3] overflow-hidden bg-sand">
              <img
                src={item.image}
                alt={item.imageAlt}
                className="h-full w-full object-cover transition-transform duration-700 group-hover:scale-105"
                loading="lazy"
              />
              <button
                type="button"
                onClick={() => setLightboxIndex(idx)}
                aria-label={`Open full preview of ${item.title}`}
                className="absolute right-3 bottom-3 inline-flex h-9 w-9 items-center justify-center rounded-sm bg-charcoal/80 text-charcoal-foreground opacity-90 transition-opacity hover:bg-bronze sm:opacity-0 sm:group-hover:opacity-100"
              >
                <Expand className="h-4 w-4" />
              </button>
            </div>
            <div className="p-5">
              <p className="text-xs font-medium tracking-widest text-bronze uppercase">
                {item.category}
              </p>
              <h3 className="mt-1.5 font-serif text-xl font-medium text-charcoal">
                {item.title}
              </h3>
              <p className="mt-2 line-clamp-2 text-sm leading-relaxed text-muted-foreground">
                {item.summary}
              </p>
              <Link
                to="/projects/$slug"
                params={{ slug: item.slug }}
                className="mt-4 inline-flex items-center gap-1.5 text-xs font-medium tracking-widest text-charcoal uppercase transition-colors hover:text-bronze"
              >
                View Details
                <ArrowUpRight className="h-3.5 w-3.5" />
              </Link>
            </div>
          </article>
        ))}
      </div>

      {activeLightboxItem && lightboxIndex !== null && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-charcoal/90 p-4 backdrop-blur-sm sm:p-8"
          role="dialog"
          aria-modal="true"
          aria-label={activeLightboxItem.title}
          onClick={() => setLightboxIndex(null)}
        >
          <div
            className="relative w-full max-w-5xl bg-card"
            onClick={(e) => e.stopPropagation()}
          >
            <button
              type="button"
              onClick={() => setLightboxIndex(null)}
              aria-label="Close lightbox"
              className="absolute top-3 right-3 z-10 inline-flex h-10 w-10 items-center justify-center rounded-sm bg-charcoal/80 text-charcoal-foreground hover:bg-bronze"
            >
              <X className="h-5 w-5" />
            </button>
            <div className="relative aspect-[16/10] w-full overflow-hidden bg-charcoal">
              <img
                src={activeLightboxItem.image}
                alt={activeLightboxItem.imageAlt}
                className="h-full w-full object-contain"
              />
              {visibleItems.length > 1 && (
                <>
                  <button
                    type="button"
                    onClick={() =>
                      setLightboxIndex(
                        (lightboxIndex - 1 + visibleItems.length) % visibleItems.length,
                      )
                    }
                    aria-label="Previous image"
                    className="absolute top-1/2 left-3 inline-flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-sm bg-charcoal/75 text-charcoal-foreground hover:bg-bronze"
                  >
                    <ChevronLeft className="h-5 w-5" />
                  </button>
                  <button
                    type="button"
                    onClick={() =>
                      setLightboxIndex((lightboxIndex + 1) % visibleItems.length)
                    }
                    aria-label="Next image"
                    className="absolute top-1/2 right-3 inline-flex h-10 w-10 -translate-y-1/2 items-center justify-center rounded-sm bg-charcoal/75 text-charcoal-foreground hover:bg-bronze"
                  >
                    <ChevronRight className="h-5 w-5" />
                  </button>
                </>
              )}
            </div>
            <div className="flex flex-col justify-between gap-3 p-5 sm:flex-row sm:items-center">
              <div>
                <p className="text-xs font-medium tracking-widest text-bronze uppercase">
                  {activeLightboxItem.locationLabel}
                </p>
                <h3 className="mt-1 font-serif text-xl font-medium text-charcoal">
                  {activeLightboxItem.title}
                </h3>
              </div>
              <Link
                to="/projects/$slug"
                params={{ slug: activeLightboxItem.slug }}
                onClick={() => setLightboxIndex(null)}
                className="inline-flex items-center gap-1.5 text-xs font-medium tracking-widest text-charcoal uppercase hover:text-bronze"
              >
                Open Project Page
                <ArrowUpRight className="h-4 w-4" />
              </Link>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}