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

// Helper pentru optimizarea imaginilor
const optimizeImageUrl = (imageUrl, width = 720, height = 720, quality = 90) => {
	if (!imageUrl) return '/images/placeholder.png';
	
	if (imageUrl.includes('amazonaws.com') || imageUrl.includes('cloudfront.net')) {
		const separator = imageUrl.includes('?') ? '&' : '?';
		return `${imageUrl}${separator}w=${width}&h=${height}&q=${quality}&f=webp`;
	}
	
	return imageUrl;
};

// Componenta de imagine optimizată pentru thumbnails
const OptimizedThumbnail = memo(({ src, alt, width = 120, height = 120 }) => {
	const [isLoaded, setIsLoaded] = useState(false);
	const [hasError, setHasError] = useState(false);

	const handleLoad = useCallback(() => {
		setIsLoaded(true);
	}, []);

	const handleError = useCallback(() => {
		setHasError(true);
	}, []);

	if (hasError) {
		return (
			<div 
				style={{ 
					width, 
					height, 
					backgroundColor: '#f5f5f5',
					display: 'flex',
					alignItems: 'center',
					justifyContent: 'center',
					color: '#999',
					fontSize: '12px',
					borderRadius: '4px'
				}}
			>
				No Image
			</div>
		);
	}

	return (
		<div style={{ position: 'relative', width, height, overflow: 'hidden', borderRadius: '4px' }}>
			{!isLoaded && (
				<div 
					style={{ 
						position: 'absolute',
						top: 0,
						left: 0,
						right: 0,
						bottom: 0,
						backgroundColor: '#f8f9fa',
						display: 'flex',
						alignItems: 'center',
						justifyContent: 'center'
					}}
				>
					<div 
						style={{ 
							width: '16px', 
							height: '16px', 
							border: '2px solid #ddd',
							borderTop: '2px solid #007bff',
							borderRadius: '50%',
							animation: 'spin 1s linear infinite'
						}} 
					/>
				</div>
			)}
			
			<Image
				src={optimizeImageUrl(src, width, height, 85)}
				alt={alt || "Thumbnail"}
				width={width}
				height={height}
				quality={85}
				priority={false}
				style={{
					objectFit: "cover",
					transition: 'opacity 0.3s ease',
					opacity: isLoaded ? 1 : 0
				}}
				onLoad={handleLoad}
				onError={handleError}
				sizes="(max-width: 768px) 60px, 120px"
			/>
		</div>
	);
});

OptimizedThumbnail.displayName = 'OptimizedThumbnail';

// Componenta de imagine optimizată pentru galeria principală - CU forwardRef
const OptimizedMainImage = memo(
	React.forwardRef(({ src, alt, width = 720, height = 720, isPriority = false }, ref) => {
		const [isLoaded, setIsLoaded] = useState(false);
		const [hasError, setHasError] = useState(false);

		const handleLoad = useCallback(() => {
			setIsLoaded(true);
		}, []);

		const handleError = useCallback(() => {
			setHasError(true);
		}, []);

		if (hasError) {
			return (
				<div 
					ref={ref}
					style={{ 
						width, 
						height, 
						backgroundColor: '#f5f5f5',
						display: 'flex',
						alignItems: 'center',
						justifyContent: 'center',
						color: '#999'
					}}
				>
					Imagine indisponibilă
				</div>
			);
		}

		return (
			<div ref={ref} style={{ position: 'relative', width: '100%', height: '100%' }}>
				{!isLoaded && (
					<div 
						style={{ 
							position: 'absolute',
							top: 0,
							left: 0,
							right: 0,
							bottom: 0,
							backgroundColor: '#f8f9fa',
							display: 'flex',
							alignItems: 'center',
							justifyContent: 'center',
							zIndex: 1
						}}
					>
						<div 
							style={{ 
								width: '32px', 
								height: '32px', 
								border: '3px solid #e9ecef',
								borderTop: '3px solid #007bff',
								borderRadius: '50%',
								animation: 'spin 1s linear infinite'
							}} 
						/>
					</div>
				)}
				
				<Image
					src={optimizeImageUrl(src, width, height, 95)}
					alt={alt || "Product image"}
					width={width}
					height={height}
					priority={isPriority}
					quality={95}
					style={{
						objectFit: "contain",
						transition: 'opacity 0.3s ease',
						opacity: isLoaded ? 1 : 0
					}}
					onLoad={handleLoad}
					onError={handleError}
					sizes="(max-width: 768px) 100vw, (max-width: 1200px) 70vw, 50vw"
				/>
			</div>
		);
	})
);

OptimizedMainImage.displayName = 'OptimizedMainImage';

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

	const optimizedImages = images?.filter(Boolean) || [];

	const handleSlideChange = useCallback((swiper) => {
		const newIndex = swiper.activeIndex;
		setCurrentSlide(newIndex);
		
		const currentImage = optimizedImages[newIndex];
		if (currentImage && typeof currentImage === 'object' && currentImage.dataValue) {
			handleColor(currentImage.dataValue);
		} else if (typeof currentImage === 'string') {
			handleColor(currentImage);
		}
	}, [optimizedImages, handleColor]);

	useEffect(() => {
		if (optimizedImages.length > 0) {
			const firstImage = typeof optimizedImages[0] === 'string' ? optimizedImages[0] : optimizedImages[0]?.src;
			if (firstImage) {
				const link = document.createElement('link');
				link.rel = 'preload';
				link.as = 'image';
				link.href = optimizeImageUrl(firstImage, 720, 720, 95);
				document.head.appendChild(link);
			}
		}
	}, [optimizedImages]);

	if (!optimizedImages.length) {
		return (
			<div className="no-images-placeholder" style={{ 
				padding: '60px', 
				textAlign: 'center', 
				color: '#666' 
			}}>
				Nu există imagini disponibile
			</div>
		);
	}

	return (
		<>
			<style jsx>{`
				@keyframes spin {
					0% { transform: rotate(0deg); }
					100% { transform: rotate(360deg); }
				}
				
				.thumbnail-container:hover {
					transform: scale(1.02);
					transition: transform 0.2s ease;
				}
				
				.main-image-container {
					cursor: zoom-in;
				}
				
				.main-image-container:hover {
					transform: scale(1.01);
					transition: transform 0.3s ease;
				}
			`}</style>

			{/* Thumbnails Swiper */}
			<Swiper
				dir='ltr'
				direction='vertical'
				spaceBetween={10}
				slidesPerView={6}
				className='tf-product-media-thumbs other-image-zoom'
				onSwiper={setThumbsSwiper}
				modules={[Thumbs]}
				watchSlidesProgress={true}
				breakpoints={{
					0: {
						direction: "horizontal",
						slidesPerView: 4,
						spaceBetween: 8,
					},
					768: {
						slidesPerView: 5,
					},
					1150: {
						direction: "vertical",
						slidesPerView: 6,
						spaceBetween: 10,
					},
				}}
			>
				{optimizedImages.map((slide, index) => {
					const imageSrc = typeof slide === 'string' ? slide : slide?.src || slide;
					
					return (
						<SwiperSlide key={`thumb-${index}`} className='stagger-item'>
							<div 
								className='item thumbnail-container'
								style={{ 
									cursor: 'pointer',
									border: currentSlide === index ? '2px solid #007bff' : '2px solid transparent',
									borderRadius: '6px',
									overflow: 'hidden'
								}}
							>
								<OptimizedThumbnail
									src={imageSrc}
									alt={`Thumbnail ${index + 1}`}
									width={120}
									height={120}
								/>
							</div>
						</SwiperSlide>
					);
				})}
			</Swiper>

			{/* Main Gallery 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={handleSlideChange}
					speed={300}
					resistance={true}
					resistanceRatio={0.85}
				>
					{optimizedImages.map((slide, index) => {
						const imageSrc = typeof slide === 'string' ? slide : slide?.src || slide;
						
						return (
							<SwiperSlide key={`main-${index}`}>
								<Item
									original={optimizeImageUrl(imageSrc, 1200, 1200, 98)}
									thumbnail={optimizeImageUrl(imageSrc, 200, 200, 80)}
									width={1200}
									height={1200}
								>
									{({ ref, open }) => (
										<div
											className='item main-image-container'
											onClick={open}
											style={{ 
												display: 'block',
												cursor: 'zoom-in'
											}}
										>
											<OptimizedMainImage
												ref={ref}
												src={imageSrc}
												alt={`Product image ${index + 1}`}
												width={720}
												height={720}
												isPriority={index === 0}
											/>
										</div>
									)}
								</Item>
							</SwiperSlide>
						);
					})}

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