'use client'

import { useState } from 'react'
import Image from 'next/image'
import ImageGallery from './ImageGallery'

interface ProductGalleryProps {
  images: string[]
  productName: string
}

export default function ProductGallery({ images, productName }: ProductGalleryProps) {
  const [galleryOpen, setGalleryOpen] = useState(false)
  const [galleryIndex, setGalleryIndex] = useState(0)

  const openGallery = (index: number = 0) => {
    setGalleryIndex(index)
    setGalleryOpen(true)
  }

  const closeGallery = () => {
    setGalleryOpen(false)
  }

  if (!images || images.length === 0) {
    return (
      <div className="w-full h-96 bg-gray-200 rounded-lg flex items-center justify-center">
        <span className="text-gray-400">Немає зображення</span>
      </div>
    )
  }

  return (
    <>
      <div className="space-y-4">
        {/* Main Image */}
        <div
          className="relative w-full h-96 bg-gray-100 rounded-lg overflow-hidden cursor-pointer hover:shadow-lg transition-shadow"
          onClick={() => openGallery(0)}
        >
          <Image
            src={images[0]}
            alt={productName}
            fill
            className="object-cover"
            priority
            sizes="(max-width: 1024px) 100vw, 50vw"
          />
          <div className="absolute inset-0 bg-black bg-opacity-0 hover:bg-opacity-10 transition-opacity flex items-center justify-center">
            <svg className="w-12 h-12 text-white opacity-0 hover:opacity-100 transition-opacity" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7" />
            </svg>
          </div>
        </div>

        {/* Thumbnail Images */}
        {images.length > 1 && (
          <div className="grid grid-cols-4 gap-2">
            {images.slice(1).map((image, index) => (
              <div
                key={index}
                className="relative w-full h-24 bg-gray-100 rounded-lg overflow-hidden cursor-pointer hover:opacity-75 hover:shadow-md transition-all"
                onClick={() => openGallery(index + 1)}
              >
                <Image
                  src={image}
                  alt={`${productName} - зображення ${index + 2}`}
                  fill
                  className="object-cover"
                  sizes="(max-width: 1024px) 25vw, 12.5vw"
                />
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Full-screen Image Gallery */}
      <ImageGallery
        images={images}
        initialIndex={galleryIndex}
        isOpen={galleryOpen}
        onClose={closeGallery}
      />
    </>
  )
}
