'use client'

import { Gallery } from '@/lib/types/product'
import React, { useState } from 'react'
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from '@/components/shadcn/ui/carousel'
import Autoplay from 'embla-carousel-autoplay'
import Image from 'next/image'

interface GalleryProps {
  galleries: Gallery[]
}

const GalleryView: React.FC<GalleryProps> = ({ galleries }) => {
  const [currentImageIndex, setCurrentImageIndex] = useState(0)

  const handleThumbnailClick = (index: number) => {
    setCurrentImageIndex(index)
  }

  return (
    <div className="w-full flex flex-col gap-2">
      {/* Main large image display */}
      <div className="overflow-hidden rounded-md w-full h-[300px] sm:h-[500px]">
        <Image
          src={galleries[currentImageIndex]?.image || galleries[0]?.image}
          alt="Featured Image"
          className="w-full object-cover h-full cursor-pointer"
          width={500}
          height={500}
        />
      </div>

      {/* Thumbnail gallery using shadcn Carousel */}
      <div className="w-full mt-2">
        <Carousel
          opts={{ loop: true, dragFree: true }}
          plugins={[Autoplay({ delay: 2000 })]}
        >
          <CarouselContent className="h-24 sm:h-32">
            {galleries.map((gallery, index) => (
              <CarouselItem
                key={gallery.id}
                className="basis-1/2 sm:basis-1/4 min-w-[80px] h-full"
              >
                <button
                  className={`w-full h-full overflow-hidden rounded-md aspect-square ${
                    currentImageIndex === index
                      ? 'border-2 border-blue-500'
                      : ''
                  }`}
                  onClick={() => handleThumbnailClick(index)}
                >
                  <Image
                    src={gallery.image}
                    alt={`Thumbnail Image`}
                    className="w-full h-full object-cover"
                    width={80}
                  />
                </button>
              </CarouselItem>
            ))}
          </CarouselContent>
          <CarouselPrevious className="left-0 top-1/2 -translate-y-1/2 -translate-x-1/4 bg-white/80 hover:bg-white shadow-md" />
          <CarouselNext className="right-0 top-1/2 -translate-y-1/2 translate-x-1/4 bg-white/80 hover:bg-white shadow-md" />
        </Carousel>
      </div>
    </div>
  )
}

export default GalleryView
