'use client';

/**
 * ============================================
 * PRODUCT IMAGE GALLERY
 * ============================================
 * Shopware-style layout:
 *  - Vertical thumbnails on the LEFT
 *  - Large main image with prev/next arrows
 *  - Dot indicators below
 *  - Click to open lightbox with zoom
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import Image from 'next/image';

interface GalleryImage {
  url: string;
  alt: string | null;
  /** Original media dimensions — used to render at natural aspect ratio (Shopware "standard" display mode). */
  width?: number;
  height?: number;
}

interface ProductImageGalleryProps {
  images: GalleryImage[];
  productName: string;
}

const THUMB_SIZE    = 70;  // px — width and height of each thumbnail
const THUMB_GAP     = 8;   // px — gap between thumbnails (gap-2)
const THUMB_STEP    = THUMB_SIZE + THUMB_GAP;
const THUMBS_VISIBLE = 5;

export default function ProductImageGallery({ images, productName }: ProductImageGalleryProps) {
  const [activeIndex, setActiveIndex] = useState(0);
  const [thumbOffset, setThumbOffset] = useState(0);   // how many thumbs scrolled past
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [zoomed, setZoomed] = useState(false);
  const [zoomPos, setZoomPos] = useState({ x: 50, y: 50 });

  const maxThumbOffset = Math.max(0, images.length - THUMBS_VISIBLE);

  const openLightbox = () => {
    setLightboxOpen(true);
    setZoomed(false);
  };

  const closeLightbox = useCallback(() => {
    setLightboxOpen(false);
    setZoomed(false);
  }, []);

  const goTo = useCallback((idx: number) => {
    setActiveIndex(idx);
    setZoomed(false);
    // Auto-scroll thumbnail strip to keep active thumb visible
    setThumbOffset(prev => {
      if (idx < prev)                          return idx;
      if (idx >= prev + THUMBS_VISIBLE)        return Math.min(idx - THUMBS_VISIBLE + 1, Math.max(0, images.length - THUMBS_VISIBLE));
      return prev;
    });
  }, [images.length]);

  const prev = useCallback(() => {
    goTo((activeIndex - 1 + images.length) % images.length);
  }, [activeIndex, images.length, goTo]);

  const next = useCallback(() => {
    goTo((activeIndex + 1) % images.length);
  }, [activeIndex, images.length, goTo]);

  useEffect(() => {
    if (!lightboxOpen) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === 'Escape') closeLightbox();
      if (e.key === 'ArrowLeft') prev();
      if (e.key === 'ArrowRight') next();
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [lightboxOpen, closeLightbox, prev, next]);

  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!zoomed) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    setZoomPos({ x, y });
  };

  if (images.length === 0) {
    return (
      <div className="bg-surface-50 rounded-2xl aspect-square flex items-center justify-center">
        <span className="text-surface-300 text-6xl">📦</span>
      </div>
    );
  }

  const activeImage = images[activeIndex];

  return (
    <>
      <div className="flex gap-4">
        {/* Vertical thumbnails on the left — max 5 visible with up/down scroll */}
        {images.length > 1 && (
          <div className="hidden sm:flex flex-col items-center gap-1 flex-shrink-0" style={{ width: `${THUMB_SIZE}px` }}>
            {/* Up arrow */}
            <button
              onClick={() => setThumbOffset(o => Math.max(0, o - 1))}
              disabled={thumbOffset === 0}
              aria-label="Previous thumbnails"
              className="flex items-center justify-center w-full h-6 text-surface-500 hover:text-brand-600 disabled:opacity-20 transition"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="18 15 12 9 6 15"/></svg>
            </button>

            {/* Viewport — clips the sliding track */}
            <div
              className="overflow-hidden w-full"
              style={{ height: `${THUMBS_VISIBLE * THUMB_STEP - THUMB_GAP}px` }}
            >
              <div
                className="flex flex-col gap-2"
                style={{
                  transform: `translateY(${-thumbOffset * THUMB_STEP}px)`,
                  transition: 'transform 0.3s ease',
                }}
              >
                {images.map((img, index) => (
                  <button
                    key={index}
                    onClick={() => goTo(index)}
                    className={`relative flex-none rounded-lg overflow-hidden border-2 transition-all ${
                      index === activeIndex
                        ? 'border-brand-500 opacity-100'
                        : 'border-surface-200 opacity-60 hover:opacity-100 hover:border-surface-400'
                    }`}
                    style={{ width: `${THUMB_SIZE}px`, height: `${THUMB_SIZE}px` }}
                    aria-label={`View image ${index + 1} of ${images.length}`}
                  >
                    <Image
                      src={img.url}
                      alt={img.alt || productName}
                      fill
                      sizes={`${THUMB_SIZE}px`}
                      className="object-contain p-1 bg-surface-50"
                    />
                  </button>
                ))}
              </div>
            </div>

            {/* Down arrow */}
            <button
              onClick={() => setThumbOffset(o => Math.min(o + 1, maxThumbOffset))}
              disabled={thumbOffset >= maxThumbOffset}
              aria-label="Next thumbnails"
              className="flex items-center justify-center w-full h-6 text-surface-500 hover:text-brand-600 disabled:opacity-20 transition"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
            </button>
          </div>
        )}

        {/* Main image with arrows */}
        <div className="relative flex-1">
          <div
            className="relative bg-surface-50 rounded-2xl overflow-hidden cursor-zoom-in group"
            onClick={openLightbox}
            title="Click to zoom"
          >
            {activeImage.width && activeImage.height ? (
              <Image
                src={activeImage.url}
                alt={activeImage.alt || productName}
                width={activeImage.width}
                height={activeImage.height}
                sizes="(max-width: 768px) 100vw, 50vw"
                className="w-full h-auto object-contain transition-transform duration-300 group-hover:scale-105"
                priority
              />
            ) : (
              // Dimensions unknown — fall back to a natural-ratio <img> so wide/tall
              // images are never letterboxed into a forced square.
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={activeImage.url}
                alt={activeImage.alt || productName}
                className="w-full h-auto object-contain transition-transform duration-300 group-hover:scale-105"
              />
            )}
          </div>

          {/* Prev/Next arrows on main image — Shopware style */}
          {images.length > 1 && (
            <>
              <button
                onClick={prev}
                className="absolute left-2 top-1/2 -translate-y-1/2 w-10 h-10 bg-white/80 hover:bg-white border border-surface-200 rounded-full flex items-center justify-center shadow-sm transition-all opacity-0 group-hover:opacity-100 hover:opacity-100"
                style={{ opacity: 1 }}
                aria-label="Previous image"
              >
                <svg className="w-5 h-5 text-surface-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                </svg>
              </button>
              <button
                onClick={next}
                className="absolute right-2 top-1/2 -translate-y-1/2 w-10 h-10 bg-white/80 hover:bg-white border border-surface-200 rounded-full flex items-center justify-center shadow-sm transition-all opacity-0 group-hover:opacity-100 hover:opacity-100"
                style={{ opacity: 1 }}
                aria-label="Next image"
              >
                <svg className="w-5 h-5 text-surface-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                </svg>
              </button>
            </>
          )}

          {/* Dot indicators below image — Shopware style */}
          {images.length > 1 && (
            <div className="flex justify-center gap-2 mt-4">
              {images.map((_, index) => (
                <button
                  key={index}
                  onClick={() => goTo(index)}
                  className="flex items-center justify-center w-6 h-6"
                  aria-label={`Go to image ${index + 1}`}
                >
                  <span
                    className={`block w-2.5 h-2.5 rounded-full transition-all ${
                      index === activeIndex
                        ? 'bg-brand-600'
                        : 'bg-surface-300 hover:bg-surface-400'
                    }`}
                  />
                </button>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Mobile thumbnails — horizontal strip below (for small screens without vertical sidebar) */}
      {images.length > 1 && (
        <div className="flex sm:hidden gap-2 overflow-x-auto pb-1 mt-3">
          {images.map((img, index) => (
            <button
              key={index}
              onClick={() => goTo(index)}
              className={`relative flex-shrink-0 w-16 h-16 rounded-lg overflow-hidden border-2 transition-all ${
                index === activeIndex
                  ? 'border-brand-500 opacity-100'
                  : 'border-surface-200 opacity-60 hover:opacity-100 hover:border-surface-400'
              }`}
              aria-label={`View image ${index + 1} of ${images.length}`}
            >
              <Image
                src={img.url}
                alt={img.alt || productName}
                fill
                sizes="64px"
                className="object-contain p-1 bg-surface-50"
              />
            </button>
          ))}
        </div>
      )}

      {/* Lightbox */}
      {lightboxOpen && (
        <div
          className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center"
          onClick={closeLightbox}
        >
          <button
            className="absolute top-4 right-4 text-white/70 hover:text-white p-2 z-10"
            onClick={closeLightbox}
            aria-label="Close"
          >
            <svg className="w-7 h-7" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>

          {images.length > 1 && (
            <>
              <button
                className="absolute left-4 top-1/2 -translate-y-1/2 text-white/70 hover:text-white p-3 z-10 bg-black/30 rounded-full"
                onClick={(e) => { e.stopPropagation(); prev(); }}
                aria-label="Previous image"
              >
                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                </svg>
              </button>
              <button
                className="absolute right-4 top-1/2 -translate-y-1/2 text-white/70 hover:text-white p-3 z-10 bg-black/30 rounded-full"
                onClick={(e) => { e.stopPropagation(); next(); }}
                aria-label="Next image"
              >
                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                </svg>
              </button>
            </>
          )}

          <div
            className={`relative w-full h-full max-w-4xl max-h-[90vh] mx-16 overflow-hidden ${
              zoomed ? 'cursor-zoom-out' : 'cursor-zoom-in'
            }`}
            onClick={(e) => { e.stopPropagation(); setZoomed((z) => !z); }}
            onMouseMove={handleMouseMove}
            onMouseLeave={() => setZoomed(false)}
          >
            <img
              src={activeImage.url}
              alt={activeImage.alt || productName}
              className="w-full h-full object-contain transition-transform duration-200 select-none"
              style={
                zoomed
                  ? { transform: 'scale(2.5)', transformOrigin: `${zoomPos.x}% ${zoomPos.y}%` }
                  : { transform: 'scale(1)' }
              }
              draggable={false}
            />
          </div>

          {images.length > 1 && (
            <div className="absolute bottom-4 left-1/2 -translate-x-1/2 text-white/60 text-sm">
              {activeIndex + 1} / {images.length}
            </div>
          )}
          <div className="absolute bottom-4 right-4 text-white/40 text-xs hidden sm:block">
            Click image to zoom · Esc to close
          </div>
        </div>
      )}
    </>
  );
}
