import { useEffect, useState } from "react";

const filterPhoto = (photo, filter) => {
  if (filter === "all") return true;
  if (filter === "named") return photo.namedFile;
  return photo.tags?.includes(filter);
};

const variantForIndex = (index) => {
  const variants = ["tall", "wide", "square", "tall", "square", "wide"];
  return variants[index % variants.length];
};

export default function FamilyAtlas({ photos = [], featured = [], filters = [] }) {
  const [activeFilter, setActiveFilter] = useState("all");
  const [lightboxIndex, setLightboxIndex] = useState(0);
  const [lightboxOpen, setLightboxOpen] = useState(false);

  const visiblePhotos = photos.filter((photo) => filterPhoto(photo, activeFilter));
  const currentPhoto = lightboxOpen ? visiblePhotos[lightboxIndex] : featured[0] ?? visiblePhotos[0] ?? null;

  useEffect(() => {
    if (!lightboxOpen) return undefined;

    const handleKeyDown = (event) => {
      if (event.key === "Escape") {
        setLightboxOpen(false);
      } else if (event.key === "ArrowRight") {
        setLightboxIndex((index) => (index + 1) % visiblePhotos.length);
      } else if (event.key === "ArrowLeft") {
        setLightboxIndex((index) => (index - 1 + visiblePhotos.length) % visiblePhotos.length);
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [lightboxOpen, visiblePhotos.length]);

  useEffect(() => {
    setLightboxIndex(0);
  }, [activeFilter]);

  const openLightbox = (index) => {
    setLightboxIndex(index);
    setLightboxOpen(true);
  };

  return (
    <section className="family-atlas" id="atlas">
      <div className="family-atlas__toolbar">
        <div className="family-atlas__topline">
          <span>Memory atlas / image-led archive test</span>
          <span>{visiblePhotos.length} visible frames</span>
        </div>

        <div className="family-atlas__filters" role="tablist" aria-label="Photo filters">
          {filters.map((filter) => (
            <button
              key={filter.key}
              type="button"
              role="tab"
              aria-selected={activeFilter === filter.key}
              className={activeFilter === filter.key ? "is-active" : ""}
              onClick={() => setActiveFilter(filter.key)}
            >
              {filter.label}
            </button>
          ))}
        </div>
      </div>

      <div className="family-atlas__layout">
        <aside className="family-atlas__inspector">
          {currentPhoto && (
            <>
              <div className="family-atlas__inspector-image">
                <img src={currentPhoto.src} alt={currentPhoto.title} loading="lazy" />
              </div>
              <div className="family-atlas__inspector-copy">
                <p className="family-atlas__inspector-kicker">Current frame</p>
                <h3>{currentPhoto.title}</h3>
                <p>{currentPhoto.description}</p>
                <div className="family-atlas__tags">
                  {(currentPhoto.tags ?? []).slice(0, 4).map((tag) => (
                    <span key={tag}>{tag.replace("-", " ")}</span>
                  ))}
                </div>
              </div>
            </>
          )}

          <div className="family-atlas__featured">
            <p className="family-atlas__inspector-kicker">Named reel</p>
            <div className="family-atlas__featured-grid">
              {featured.slice(0, 4).map((photo) => (
                <button
                  key={photo.filename}
                  type="button"
                  onClick={() => {
                    const nextIndex = visiblePhotos.findIndex((item) => item.filename === photo.filename);
                    if (nextIndex >= 0) {
                      openLightbox(nextIndex);
                    }
                  }}
                >
                  <img src={photo.src} alt={photo.title} loading="lazy" />
                  <span>{photo.title}</span>
                </button>
              ))}
            </div>
          </div>
        </aside>

        <div className="family-atlas__masonry">
          {visiblePhotos.map((photo, index) => (
            <button
              key={photo.filename}
              type="button"
              className={`family-atlas__tile family-atlas__tile--${variantForIndex(index)}`}
              onClick={() => openLightbox(index)}
            >
              <img src={photo.src} alt={photo.title} loading="lazy" />
              <span className="family-atlas__tile-meta">
                <strong>{photo.title}</strong>
                <small>{photo.namedFile ? "named frame" : "archive frame"}</small>
              </span>
            </button>
          ))}
        </div>
      </div>

      {lightboxOpen && currentPhoto && (
        <div
          className="family-lightbox"
          role="dialog"
          aria-modal="true"
          aria-label={`${currentPhoto.title} lightbox`}
          onClick={() => setLightboxOpen(false)}
        >
          <div className="family-lightbox__sheet" onClick={(event) => event.stopPropagation()}>
            <button
              type="button"
              className="family-lightbox__close"
              onClick={() => setLightboxOpen(false)}
              aria-label="Close lightbox"
            >
              Close
            </button>

            <div className="family-lightbox__frame">
              <button
                type="button"
                className="family-lightbox__nav family-lightbox__nav--prev"
                onClick={() => setLightboxIndex((index) => (index - 1 + visiblePhotos.length) % visiblePhotos.length)}
                aria-label="Previous image"
              >
                Previous
              </button>

              <img src={currentPhoto.src} alt={currentPhoto.title} />

              <button
                type="button"
                className="family-lightbox__nav family-lightbox__nav--next"
                onClick={() => setLightboxIndex((index) => (index + 1) % visiblePhotos.length)}
                aria-label="Next image"
              >
                Next
              </button>
            </div>

            <div className="family-lightbox__caption">
              <p className="family-atlas__inspector-kicker">
                Frame {lightboxIndex + 1} / {visiblePhotos.length}
              </p>
              <h3>{currentPhoto.title}</h3>
              <p>{currentPhoto.description}</p>
              <div className="family-atlas__tags">
                {(currentPhoto.tags ?? []).map((tag) => (
                  <span key={tag}>{tag.replace("-", " ")}</span>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </section>
  );
}
