import React, { useEffect, useState } from 'react';
import Icon from '../../shared/components/icon';

export interface GalleryImage {
  src: string;
  alt?: string;
  caption?: string;
}

export interface GalleryProps {
  title?: string;
  intro?: string;
  images: GalleryImage[];
}

const PhotoGallery: React.FC<GalleryProps> = ({ images, title, intro }) => {
  const [activeIndex, setActiveIndex] = useState<number | null>(null);

  const isOpen = activeIndex !== null;
  const activeImage = activeIndex !== null ? images[activeIndex] : null;

  const close = () => setActiveIndex(null);

  const next = () => {
    if (activeIndex === null) return;
    setActiveIndex((activeIndex + 1) % images.length);
  };

  const prev = () => {
    if (activeIndex === null) return;
    setActiveIndex((activeIndex - 1 + images.length) % images.length);
  };

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

    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') close();
      if (e.key === 'ArrowRight') next();
      if (e.key === 'ArrowLeft') prev();
    };

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

    return () => {
      document.removeEventListener('keydown', onKeyDown);
      document.body.style.overflow = '';
    };
  }, [isOpen, activeIndex, images.length]);

  if (!images.length) {
    return (
      <section className="gallery">
        <p className="gallery__empty">No photos available.</p>
      </section>
    );
  }

  const big = images[0];
  const thumbs = images.slice(1, 6);
  const extraCount = Math.max(0, images.length - 6);

  const openAt = (index: number) => {
    if (!images[index]) return;
    setActiveIndex(index);
  };

  return (
    <div className="content">
      <div className="content__container">
        <div className="content__colums content__colums--2-1">
          <section className="gallery">
            <div className="gallery__layout">
              <button type="button" className="gallery__big" onClick={() => openAt(0)} aria-label="Open image 1">
                <img className="gallery__big__img" src={big.src} alt={big.alt ?? ''} loading="eager" />
              </button>

              <div className="gallery__thumbs" aria-label="Gallery thumbnails">
                {thumbs.map((img, i) => {
                  const realIndex = i + 1;
                  const isLastThumbSlot = i === 4;
                  const shouldShowMoreOverlay = isLastThumbSlot && extraCount > 0;

                  return (
                    <button
                      key={`${img.src}-${realIndex}`}
                      type="button"
                      className={`gallery__thumb ${shouldShowMoreOverlay ? 'gallery__thumb--more' : ''}`}
                      onClick={() => openAt(realIndex)}
                      aria-label={`Open image ${realIndex + 1}`}>
                      <img className="gallery__thumb__img" src={img.src} alt={img.alt ?? ''} loading="lazy" />

                      {shouldShowMoreOverlay && (
                        <span className="gallery__thumb__overlay" aria-label={`${extraCount} more photos`}>
                          +{extraCount}
                        </span>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>

            {isOpen && activeImage && (
              <div
                className="gallery__lightbox"
                role="dialog"
                aria-modal="true"
                onMouseDown={(e) => {
                  if (e.target === e.currentTarget) close();
                }}>
                <div className="gallery__lightbox__panel">
                  <button type="button" className="gallery__btn__icon gallery__btn__icon--close" aria-label="Close" onClick={close}>
                    <Icon name="ui-close" width={16} height={16} />
                  </button>

                  <div className="gallery__lightbox__media">
                    <img className="gallery__lightbox__img" src={activeImage.src} alt={activeImage.alt ?? ''} />
                  </div>

                  <div className="gallery__lightbox__footer">
                    <div className="gallery__lightbox__info">
                      <span className="gallery__lightbox__index">
                        {activeIndex + 1} / {images.length}
                      </span>
                      {(activeImage.caption || activeImage.alt) && <span className="gallery__lightbox__caption">{activeImage.caption ?? activeImage.alt}</span>}
                    </div>

                    <div className="gallery__lightbox__controls">
                      <button type="button" className="gallery__btn" onClick={prev}>
                        ←
                      </button>
                      <button type="button" className="gallery__btn" onClick={next}>
                        →
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </section>
          <div>
            <h2 className="gallery__title">{title}</h2>
            <p className="gallery__text">{intro}</p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PhotoGallery;
