'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { ChevronLeft, ChevronRight, X } from 'lucide-react';

interface GalleryAlbumsProps {
  items: any[];
}

export default function GalleryAlbums({ items }: GalleryAlbumsProps) {
  const albums = useMemo(
    () =>
      items.map((item: any) => ({
        _id: item._id,
        name: item.name || item.title || 'Untitled Gallery',
        images: item.images && item.images.length > 0 ? item.images : item.imageUrl ? [item.imageUrl] : [],
      })),
    [items]
  );

  const [viewer, setViewer] = useState<{ albumIndex: number; imageIndex: number } | null>(null);

  useEffect(() => {
    if (!viewer) return;

    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setViewer(null);
        return;
      }
      if (e.key === 'ArrowRight') {
        goNext();
        return;
      }
      if (e.key === 'ArrowLeft') {
        goPrev();
      }
    };

    document.body.style.overflow = 'hidden';
    window.addEventListener('keydown', onKeyDown);

    return () => {
      document.body.style.overflow = '';
      window.removeEventListener('keydown', onKeyDown);
    };
  }, [viewer]);

  const goNext = () => {
    if (!viewer) return;
    const album = albums[viewer.albumIndex];
    if (!album || album.images.length === 0) return;
    setViewer({
      albumIndex: viewer.albumIndex,
      imageIndex: (viewer.imageIndex + 1) % album.images.length,
    });
  };

  const goPrev = () => {
    if (!viewer) return;
    const album = albums[viewer.albumIndex];
    if (!album || album.images.length === 0) return;
    setViewer({
      albumIndex: viewer.albumIndex,
      imageIndex: (viewer.imageIndex - 1 + album.images.length) % album.images.length,
    });
  };

  return (
    <>
      <div className="space-y-12">
        {albums.map((album, albumIndex) => (
          <section
            key={album._id}
            className="relative overflow-hidden rounded-3xl border border-slate-200 bg-white shadow-[0_22px_45px_-35px_rgba(15,23,42,0.55)]"
          >
            <div className="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-[#0E3A8A] via-[#16A34A] to-[#BE123C]"></div>
            <div className="px-6 md:px-10 pt-8 pb-3">
              <p className="text-[11px] uppercase tracking-[0.2em] font-semibold text-slate-500 mb-2">Gallery</p>
              <h2 className="text-2xl md:text-4xl font-bold text-slate-900 leading-tight">{album.name}</h2>
              <p className="text-sm text-slate-500 mt-2">{album.images.length} photos</p>
            </div>

            <div className="px-4 md:px-8 pb-8 columns-2 md:columns-3 lg:columns-4 gap-4 md:gap-5 space-y-4 md:space-y-5">
              {album.images.map((img: string, idx: number) => (
                <button
                  key={`${img}-${idx}`}
                  type="button"
                  className="group block w-full text-left break-inside-avoid rounded-2xl overflow-hidden bg-slate-100 border border-slate-200/80 shadow-[0_16px_26px_-20px_rgba(15,23,42,0.7)] hover:shadow-[0_24px_40px_-24px_rgba(15,23,42,0.75)] transition-all duration-300"
                  onClick={() => setViewer({ albumIndex, imageIndex: idx })}
                >
                  <div className="relative">
                    <img
                      src={img}
                      alt={album.name}
                      loading="lazy"
                      className="w-full h-auto object-cover group-hover:scale-[1.04] transition-transform duration-500"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/35 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                  </div>
                </button>
              ))}
            </div>
          </section>
        ))}
      </div>

      {viewer && (
        <div className="fixed inset-0 z-[100] bg-black/90 backdrop-blur-md flex items-center justify-center p-4">
          <button
            type="button"
            onClick={() => setViewer(null)}
            className="absolute top-4 right-4 p-2.5 rounded-full bg-white/15 text-white hover:bg-white/25 transition"
            aria-label="Close"
          >
            <X size={22} />
          </button>

          <button
            type="button"
            onClick={goPrev}
            className="absolute left-4 md:left-8 p-2.5 rounded-full bg-white/15 text-white hover:bg-white/25 transition"
            aria-label="Previous image"
          >
            <ChevronLeft size={28} />
          </button>

          <div className="max-w-6xl max-h-[88vh] w-full flex items-center justify-center rounded-xl overflow-hidden border border-white/10 shadow-2xl">
            <img
              src={albums[viewer.albumIndex].images[viewer.imageIndex]}
              alt={albums[viewer.albumIndex].name}
              className="max-w-full max-h-[88vh] object-contain rounded-lg"
            />
          </div>

          <button
            type="button"
            onClick={goNext}
            className="absolute right-4 md:right-8 p-2.5 rounded-full bg-white/15 text-white hover:bg-white/25 transition"
            aria-label="Next image"
          >
            <ChevronRight size={28} />
          </button>

          <div className="absolute bottom-4 left-1/2 -translate-x-1/2 px-4 py-2 rounded-full bg-white/10 border border-white/15 text-white text-sm backdrop-blur">
            {albums[viewer.albumIndex].name} • {viewer.imageIndex + 1}/{albums[viewer.albumIndex].images.length}
          </div>
        </div>
      )}
    </>
  );
}
