"use client";

import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import { Gallery, Item } from "react-photoswipe-gallery";
import { Navigation, Thumbs } from "swiper/modules";
import { Swiper, SwiperSlide } from "swiper/react";

export default function SliderWithGalleryPopup({
	currentColor = "Beige",
	handleColor = () => {},
	images,
}) {
	console.log(images);
	const [thumbsSwiper, setThumbsSwiper] = useState(null);
	const swiperRef = useRef(null);

	return (
		<>
			<Swiper
				dir='ltr'
				direction='vertical'
				spaceBetween={10}
				slidesPerView={6}
				className='tf-product-media-thumbs other-image-zoom'
				onSwiper={setThumbsSwiper}
				modules={[Thumbs]}
				breakpoints={{
					0: {
						direction: "horizontal",
					},
					1150: {
						direction: "vertical",
					},
				}}
			>
				{images.map((slide, index) => (
					<SwiperSlide key={index} className='stagger-item'>
						<div className='item'>
							<Image
								className='lazyload'
								data-src={slide}
								alt={""}
								src={slide} 
								width={720}
								height={720}
							/>
						</div>
					</SwiperSlide>
				))}
			</Swiper>
			<Gallery>
				<Swiper
					dir='ltr'
					spaceBetween={10}
					slidesPerView={1}
					navigation={{
						nextEl: ".swiper-button-next",
						prevEl: ".swiper-button-prev",
					}}
					className='tf-product-media-main tf-product-zoom-inner'
					id='gallery-swiper-started'
					thumbs={{ swiper: thumbsSwiper }}
					modules={[Thumbs, Navigation]}
					onSwiper={(swiper) => (swiperRef.current = swiper)}
					onSlideChange={(swiper) => {
						handleColor(images[swiper.activeIndex].dataValue);
					}}
				>
					{images.map((slide, index) => (
						<SwiperSlide key={index}>
							<Item
								original={slide}
								thumbnail={slide}
								width={720}
								height={720}
							>
								{({ ref, open }) => (
									<a
										className='item'
										data-pswp-width={720}
										data-pswp-height={
											720
										}
										onClick={open}
									>
										<Image
											className='tf-image-zoom-magnifier ls-is-cached lazyloaded'
											data-zoom={slide}
											data-src={slide}
											ref={ref}
											alt='image'
											width={720}
											height={720}
											src={slide} // Optional fallback for non-lazy loading
										/>
									</a>
								)}
							</Item>
						</SwiperSlide>
					))}

					{/* Navigation buttons */}
					<div className='swiper-button-next button-style-arrow thumbs-next'></div>
					<div className='swiper-button-prev button-style-arrow thumbs-prev'></div>
				</Swiper>
			</Gallery>
		</>
	);
}
