"use client";
import Image from "next/image";
import Link from "next/link";
import { Heart } from "lucide-react";
import { useState, memo, useCallback } from "react";
import { useContextElement } from "@/context/Context";
import { getProductCoin, getProductLanguage, getProductPrice, useT } from "@/context/I18nContext";

// Helper pentru optimizarea imaginilor AWS
const optimizeImageUrl = (imageUrl, width = 260, height = 260, quality = 40) => {
	if (!imageUrl) return '/images/placeholder.png';
	
     imageUrl = imageUrl.replace('/products/', '/productscards/'); 

	// Dacă e de pe AWS S3/CloudFront, adaugă parametri de optimizare
	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ă
const OptimizedImage = memo(({ src, alt, width, height }) => {
	const [imageError, setImageError] = useState(false);
	const [isLoaded, setIsLoaded] = useState(false);

	const handleImageError = useCallback(() => {
		setImageError(true);
	}, []);

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

	if (imageError) {
		return (
			<div 
				className="placeholder-image"
				style={{ 
					width, 
					height, 
					backgroundColor: '#f5f5f5',
					display: 'flex',
					alignItems: 'center',
					justifyContent: 'center',
					color: '#999'
				}}
			>
				No Image
			</div>
		);
	}

	return (
		<>
			{/* Placeholder în timpul încărcării */}
			{!isLoaded && (
				<div 
					style={{ 
						position: 'absolute',
						top: 0,
						left: 0,
						right: 0,
						bottom: 0,
						backgroundColor: '#f5f5f5',
						display: 'flex',
						alignItems: 'center',
						justifyContent: 'center',
						borderRadius: '8px'
					}}
				>
					<div className="loading-spinner" style={{ 
						width: '24px', 
						height: '24px', 
						border: '2px solid #ddd',
						borderTop: '2px solid #007bff',
						borderRadius: '50%',
						animation: 'spin 1s linear infinite'
					}} />
				</div>
			)}
			
			<Image
				src={optimizeImageUrl(src, width, height)}
				alt={alt}
				width={width}
				height={height}
				loading="lazy" // Lazy loading nativ
				quality={80}
				style={{
					objectFit: "contain",
					backgroundColor: "#fff",
					transition: 'opacity 0.3s ease',
					opacity: isLoaded ? 1 : 0
				}}
				placeholder='blur'
				blurDataURL='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAv/xAAhEAACAQMDBQAAAAAAAAAAAAABAgMABAUGIWGBobHB0eH/xAAUAQEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/2gAMAwEAAhEDEQA/AKrjM5upSlxkIS6bV1d5s59e5YkI1b5h7r6vvGZh7LdyVZ5Aui6xeZIqLbVpqVs99JZl6YqL4AUQKVpKV5O/1v/Z'
				onError={handleImageError}
				onLoad={handleImageLoad}
				sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"
                    unoptimized
			/>
		</>
	);
});

OptimizedImage.displayName = 'OptimizedImage';

// Componenta principală optimizată
export const ProductCard = memo(({ product }) => {
     const { t } = useT(); 

	const { addToWishlist, isAddedtoWishlist, addProductToCart, isAddedToCartProducts } = useContextElement();
	
	// Calculează primul imagine
	const mainImage = product.images?.split("|").filter(Boolean)[0];
	
	// Handler optimizat pentru wishlist
	const handleWishlistToggle = useCallback((e) => {
		e.preventDefault();
		addToWishlist(product.id);
	}, [addToWishlist, product.id]);

	// Check dacă e în wishlist (memoized)
	const isInWishlist = isAddedtoWishlist(product.id);

	return (
		<div
			className='card-product fl-item'
			style={{
				position: "relative",
				boxShadow: "0px 4px 10px rgba(0, 0, 0, 0.1)",
				borderRadius: "10px",
				padding: "10px",
				transition: "transform 0.2s ease-in-out",
			}}>
			
			<div className='card-product-wrapper' style={{ position: "relative", height: "260px" }}>
				<Link 
					href={`/${product.url}`} 
					className='product-img' 
					style={{ 
						justifyContent: "center",
						position: "relative",
						display: "block",
						height: "100%"
					}}
				>
					<OptimizedImage
						src={mainImage}
						alt={product.name}
						width={260}
						height={260}
					/>
				</Link>

				{/* Wishlist button optimizat */}
				<button
					onClick={handleWishlistToggle}
					className="wishlist-btn"
					style={{
						position: "absolute",
						top: "10px",
						right: "10px",
						padding: "8px",
						borderRadius: "50%",
						backgroundColor: isInWishlist ? "#e53e3e" : "#ffffff",
						color: isInWishlist ? "#ffffff" : "#6b7280",
						border: "none",
						boxShadow: "0 2px 5px rgba(0,0,0,0.2)",
						cursor: "pointer",
						transition: "all 0.2s ease",
						zIndex: 2
					}}
					aria-label='Adauga la favorite'>
					<Heart 
						fill={isInWishlist ? "currentColor" : "none"} 
						size={20} 
					/>
				</button>
			</div>

			<div className='card-product-info'>
				<Link href={`/${product.url}`} className='title link'>
					{getProductLanguage(product)}
				</Link>

				<div className='price-section' style={{ marginTop: '8px' }}>
					<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
						<div>
							{product.priceReduced && (
								<div
									style={{ 
										fontSize: "14px", 
										color: "red",
										textDecoration: "line-through",
										marginBottom: "4px"
									}}>
									{getProductPrice(product.price)} {getProductCoin()}
								</div>
							)}
							
							<div style={{ 
								color: "#2b9d31ff", 
								fontWeight: "bold", 
								fontSize: "18px" 
							}}>
								{product.priceReduced ? getProductPrice(product.priceReduced) : getProductPrice(product.price)} <span style={{ fontSize: "14px", color: "#333" }}>{getProductCoin()}</span>
                                        {product.stock === 0 && (
                                             <>
                                             <span style={{ fontSize: "14px" }}><br/><small style={{color:'brown'}}>{t("produs_out_of_stock")}</small></span>
                                             </>
                                        )}
							</div>
						</div>

						<button
							className='btn btn-primary btn-sm rounded-circle d-flex align-items-center justify-content-center'
							style={{ 
								width: "40px", 
								height: "40px",
								flexShrink: 0,
                                        backgroundColor: isAddedToCartProducts(product.id) ? 'red' : '#007bff'
							}}
                                   onClick={() => {
                                                       
                                        addProductToCart(
                                             product.id
                                        );
                                   }}
							aria-label='Adauga in cos'>
							<i className='icon icon-bag' style={{ fontSize: "18px"}} />
						</button>
					</div>
				</div>
			</div>

			{/* CSS pentru animații și spinner */}
			<style jsx>{`
				@keyframes spin {
					0% { transform: rotate(0deg); }
					100% { transform: rotate(360deg); }
				}
				
				.wishlist-btn:hover {
					background-color: #e53e3e !important;
					color: #ffffff !important;
					transform: scale(1.05);
				}
				
				.card-product:hover {
					transform: translateY(-2px);
				}
			`}</style>
		</div>
	);
});

ProductCard.displayName = 'ProductCard';