"use client";
import React, { useMemo, useState, useEffect } from "react";
import Image from "next/image";
import { Container } from "../ui/container";
import {
    Breadcrumb,
    BreadcrumbItem,
    BreadcrumbLink,
    BreadcrumbList,
    BreadcrumbPage,
    BreadcrumbSeparator,
} from "../ui/breadcrumb";
import { TypographyH3, TypographyH4 } from "../ui/typography";
import { Separator } from "../ui/separator";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { ProductDetailData, SelectedVariant } from '@/types/api';
import { ProductDetailService } from '@/services/productDetailService';
import { discountService, DiscountValidationResponse } from '@/services/discountService';
import { useCart } from '@/context/CartContext';
import { useToast } from '@/context/ToastContext';

type PDImage = { id: string; src: string; alt: string };

interface ProductDetailsProps {
  slug?: string;
}

const renderStars = (rating: number) => {
    const full = Math.floor(rating);
    const half = rating - full >= 0.5;
    return (
        <div className="flex items-center gap-1.5">
            {Array.from({ length: 5 }).map((_, i) => {
                const isFull = i < full;
                const isHalf = i === full && half;
                const src = isFull
                    ? "/assets/icons/full-star.svg"
                    : isHalf
                        ? "/assets/icons/half-star.svg"
                        : "/assets/icons/full-star.svg";
                const cls =
                    isFull || isHalf
                        ? "w-[18.49px] h-[18.49px]"
                        : "w-[18.49px] h-[18.49px] opacity-30";
                const alt = isFull ? "full-star" : isHalf ? "half-star" : "empty-star";
                return (
                    <Image
                        key={i}
                        src={src}
                        alt={alt}
                        width={19}
                        height={19}
                        className={cls}
                    />
                );
            })}
        </div>
    );
};

const ProductDetails: React.FC<ProductDetailsProps> = ({ slug }) => {
    const t = {
        home: 'الرئيسية',
        shop: 'المتجر',
        selectColors: 'اختيار الألوان',
        chooseSize: 'اختيار المقاس',
        onlyLeft: (n: number) => `المتبقي فقط ${n} في المخزون`,
        inStock: 'متوفر في المخزون',
        promotionCode: 'رمز الخصم',
        enterPromo: 'أدخل رمز الخصم',
        checking: 'جاري التحقق...',
        applied: 'تم التطبيق',
        apply: 'تطبيق',
        codeApplied: 'تم تطبيق الرمز بنجاح!',
        addedToCart: 'تمت الإضافة للسلة!',
        adding: 'جاري الإضافة...',
        outOfStock: 'غير متوفر',
        addToCart: 'أضف إلى السلة',
        ratingLabel: (r: number) => `${r.toFixed(1)}/5`,
        productNotFoundTitle: 'المنتج غير موجود',
        productNotFoundDesc: 'المنتج الذي تبحث عنه غير موجود.',
        discountBadge: 'خصم',
    };
    const { addToCart } = useCart();
    const { showToast } = useToast();
    const [product, setProduct] = useState<ProductDetailData | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    
    // Component state
    const [activeImageIndex, setActiveImageIndex] = useState(0);
    const [selectedColor, setSelectedColor] = useState<string>('');
    const [selectedSize, setSelectedSize] = useState<string>('');
    const [qty, setQty] = useState<number>(1);
    const [promoCode, setPromoCode] = useState<string>('');
    const [promoApplied, setPromoApplied] = useState(false);
    const [promoLoading, setPromoLoading] = useState(false);
    const [promoError, setPromoError] = useState<string>('');
    const [discountData, setDiscountData] = useState<DiscountValidationResponse | null>(null);
    const [isAddingToCart, setIsAddingToCart] = useState(false);
    const [justAdded, setJustAdded] = useState(false);
    const [selectedVariant, setSelectedVariant] = useState<SelectedVariant>({
        price: 0,
        stock: 0
    });

    const disabledMinus = useMemo(() => qty <= 1, [qty]);

    // Fetch product data
    useEffect(() => {
        if (!slug) {
            console.log('ProductDetailsWithAPI: No slug provided');
            return;
        }

        const fetchProduct = async () => {
            setLoading(true);
            setError(null);

            try {
                console.log('ProductDetailsWithAPI: Fetching product with slug:', slug);
                const productData = await ProductDetailService.getProductBySlug(slug);
                console.log('ProductDetailsWithAPI: Product data received:', productData);
                
                // Validate essential data
                if (!productData || !productData.id) {
                    throw new Error('Invalid product data structure');
                }
                
                setProduct(productData);

                // Set initial selections
                if (productData.availableColors.length > 0) {
                    setSelectedColor(productData.availableColors[0]);
                    console.log('ProductDetailsWithAPI: Set initial color:', productData.availableColors[0]);
                }
                if (productData.availableSizes.length > 0) {
                    setSelectedSize(productData.availableSizes[0]);
                    console.log('ProductDetailsWithAPI: Set initial size:', productData.availableSizes[0]);
                }

                // Set initial variant
                const initialVariant = ProductDetailService.getSelectedVariant(
                    productData,
                    productData.availableSizes[0],
                    productData.availableColors[0]
                );
                console.log('ProductDetailsWithAPI: Initial variant:', initialVariant);
                setSelectedVariant(initialVariant);
            } catch (err) {
                console.error('ProductDetailsWithAPI: Error fetching product:', err);
                const errorMessage = err instanceof Error ? err.message : 'Product not found';
                console.error('ProductDetailsWithAPI: Error message:', errorMessage);
                setError(errorMessage);
            } finally {
                setLoading(false);
            }
        };

        fetchProduct();
    }, [slug]);

    // Update selected variant when color or size changes
    useEffect(() => {
        if (!product) return;

        const newVariant = ProductDetailService.getSelectedVariant(
            product,
            selectedSize,
            selectedColor
        );
        setSelectedVariant(newVariant);

        // Reset quantity if it exceeds new stock
        if (qty > newVariant.stock) {
            setQty(Math.max(1, newVariant.stock));
        }
    }, [product, selectedSize, selectedColor, qty]);

    const handleApplyPromoCode = async () => {
        if (!promoCode.trim()) {
            setPromoError('Please enter a promotion code');
            return;
        }

        setPromoLoading(true);
        setPromoError('');

        try {
            // Validate the promo code with the API
            const result = await discountService.validateCode(
                promoCode.trim(),
                undefined, // We don't have order amount yet on product page
                product?.id
            );

            if (result.valid) {
                setPromoApplied(true);
                setDiscountData(result);
                setPromoError('');
            } else {
                setPromoApplied(false);
                setDiscountData(null);
                setPromoError(result.message || 'Invalid promotion code');
            }
        } catch (error) {
            console.error('Error validating promo code:', error);
            setPromoApplied(false);
            setDiscountData(null);
            setPromoError('Failed to validate promotion code. Please try again.');
        } finally {
            setPromoLoading(false);
        }
    };

    // Calculate discounted price if promo is applied
    const finalPrice = useMemo(() => {
        if (!promoApplied || !discountData || !discountData.type || !discountData.value) {
            return selectedVariant.price;
        }

        const discountAmount = discountService.calculateDiscount(
            discountData.type,
            discountData.value,
            selectedVariant.price
        );

        return selectedVariant.price - discountAmount;
    }, [promoApplied, discountData, selectedVariant.price]);

    const handleAddToCart = async () => {
        if (!product || !selectedVariant.variant || isAddingToCart) return;

        setIsAddingToCart(true);
        
        try {
            // Add product to cart using the cart context
            await addToCart({
                id: product.id.toString(),
                title: product.name,
                price: selectedVariant.price,
                imageSrc: product.images[0] || '/assets/placeholder.png',
                slug: product.slug,
            }, qty);
            
            // Trigger success animation
            setJustAdded(true);
            setTimeout(() => setJustAdded(false), 1500);
            
            showToast({
                type: 'success',
                title: 'Added to Cart',
                description: `${product.name} (${qty} item${qty > 1 ? 's' : ''}) added to cart`,
                duration: 2000,
            });
        } catch (err) {
            console.error('Cart error:', err);
            showToast({
                type: 'error',
                title: 'Error',
                description: 'Failed to add item to cart',
                duration: 3000,
            });
        } finally {
            setIsAddingToCart(false);
        }
    };

    if (loading) {
        return (
            <div className="w-full px-4 md:px-6 mb-14 md:mb-[60px]">
                <Container>
                    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 xl:gap-10">
                        {/* Image skeleton */}
                        <div className="flex flex-col-reverse sm:flex-row gap-3.5">
                            <div className="flex flex-row sm:flex-col gap-3.5">
                                {[...Array(3)].map((_, i) => (
                                    <div key={i} className="w-[152px] h-[100px] sm:h-[165px] bg-gray-200 rounded-xl animate-pulse" />
                                ))}
                            </div>
                            <div className="w-full h-[400px] sm:h-[530px] bg-gray-200 rounded-xl animate-pulse" />
                        </div>
                        
                        {/* Content skeleton */}
                        <div className="space-y-6">
                            <div className="h-8 bg-gray-200 rounded animate-pulse" />
                            <div className="h-4 bg-gray-200 rounded animate-pulse w-3/4" />
                            <div className="h-20 bg-gray-200 rounded animate-pulse" />
                        </div>
                    </div>
                </Container>
            </div>
        );
    }

    if (error || !product) {
        return (
            <div className="w-full px-4 md:px-6 mb-14 md:mb-[60px]">
                <Container>
                    <div className="text-center py-20">
                        <h1 className="text-2xl font-bold text-gray-900 mb-4">{t.productNotFoundTitle}</h1>
                        <p className="text-gray-600">{t.productNotFoundDesc}</p>
                    </div>
                </Container>
            </div>
        );
    }

    // Prepare images for display
    const displayImages: PDImage[] = product.images.map((src, index) => ({
        id: `img-${index}`,
        src: src,
        alt: `${product.name} - Image ${index + 1}`
    }));

    // Fallback if no images
    if (displayImages.length === 0) {
        displayImages.push({
            id: 'placeholder',
            src: '/assets/placeholder.png',
            alt: product.name
        });
    }

    const activeImage = displayImages[activeImageIndex] || displayImages[0];

    // Prepare colors for display (convert to your design format)
    const colors = product.availableColors.map((color) => ({
        id: color,
        name: color,
        hex: getColorHex(color) // Helper function to get hex color
    }));

    // Calculate discount percentage
    const discountPercentage = selectedVariant.variant && selectedVariant.variant.price !== product.base_price 
        ? Math.round(((product.base_price - selectedVariant.price) / product.base_price) * 100)
        : 0;

    return (
        <div className="w-full px-4 md:px-6 mb-14 md:mb-[60px] overflow-x-hidden overflow-y-hidden">
            <Container className="relative">
                <Image src='/assets/icons/star.svg' alt="star" width={22} height={22} className="absolute -right-5 sm:right-1 xl:-right-10 top-[620px] lg:top-[77px]" />
                <Image src='/assets/icons/line-2.svg' alt="line" width={97} height={6} className="absolute -right-14 sm:right-6 xl:-right-4 top-[680px] lg:top-[130px]" />
                
                <Breadcrumb className="mb-5 md:mb-9">
                    <BreadcrumbList>
                        <BreadcrumbItem>
                            <BreadcrumbLink href="/">{t.home}</BreadcrumbLink>
                        </BreadcrumbItem>
                        <BreadcrumbSeparator />
                        <BreadcrumbItem>
                            <BreadcrumbLink href="/products">{t.shop}</BreadcrumbLink>
                        </BreadcrumbItem>
                        <BreadcrumbSeparator />
                        <BreadcrumbItem>
                            <BreadcrumbLink href={`/products?category=${product.category.slug}`}>
                                {product.category.name}
                            </BreadcrumbLink>
                        </BreadcrumbItem>
                        <BreadcrumbSeparator />
                        <BreadcrumbItem>
                            <BreadcrumbPage>{product.name}</BreadcrumbPage>
                        </BreadcrumbItem>
                    </BreadcrumbList>
                </Breadcrumb>

                <div className="grid grid-cols-1 lg:grid-cols-[minmax(0,550px)_minmax(0,1fr)] xl:grid-cols-[minmax(0,610px)_minmax(0,1fr)] gap-6 xl:gap-10">
                    {/* Left: Gallery */}
                    <div className="lg:max-w-[610px] w-full flex sm:flex-row flex-col-reverse items-start gap-3.5">
                        <div className="flex flex-row sm:flex-col gap-3.5 min-w-[152px]">
                            {displayImages.map((img, index) => (
                                <button
                                    key={img.id}
                                    onClick={() => setActiveImageIndex(index)}
                                    className={`rounded-xl sm:rounded-[20px] bg-[#F0EEED] cursor-pointer border ${activeImageIndex === index
                                        ? "border-black"
                                        : "border-transparent"
                                        }`}
                                >
                                    <div className="w-full h-[100px] sm:h-[165px] rounded-[20px] overflow-hidden flex items-center justify-center bg-[#F0EEED] relative">
                                        {img.src.startsWith('data:image') ? (
                                            // Use Next.js Image with unoptimized for base64 images
                                            <Image
                                                src={img.src}
                                                alt={img.alt}
                                                fill
                                                unoptimized
                                                className="object-cover"
                                            />
                                        ) : (
                                            // Use Next.js Image component for URLs
                                            <Image
                                                src={img.src}
                                                alt={img.alt}
                                                fill
                                                className="object-cover"
                                            />
                                        )}
                                    </div>
                                </button>
                            ))}
                        </div>
                        <div className="rounded-xl sm:rounded-[20px] bg-[#F0EEED] w-full lg:max-w-[444px] h-[400px] sm:h-[530px] flex items-center justify-center overflow-hidden relative">
                            {activeImage.src.startsWith('data:image') ? (
                                // Use Next.js Image with unoptimized for base64 images
                                <Image
                                    src={activeImage.src}
                                    alt={activeImage.alt}
                                    fill
                                    unoptimized
                                    className="object-cover"
                                />
                            ) : (
                                // Use Next.js Image component for URLs
                                <Image
                                    src={activeImage.src}
                                    alt={activeImage.alt}
                                    fill
                                    className="object-cover"
                                />
                            )}
                        </div>
                    </div>

                    {/* Right: Details */}
                    <div className="w-full lg:max-w-[590px]">
                        <TypographyH3 className="text-[28px] sm:text-[32px] xl:text-[40px] leading-10 sm:leading-[42px] xl:leading-[60px] font-extrabold prompt">
                            {product.name}
                        </TypographyH3>

                        <div className="mt-2 flex items-center gap-3 sm:gap-4">
                            {renderStars(4.5)} {/* You can make this dynamic later */}
                            <span className="text-[#667085] text-sm">{t.ratingLabel(4.5)}</span>
                        </div>

                        <div className="mt-3.5 flex items-center gap-3 flex-wrap">
                            <span className="text-[28px] md:text-[32px] leading-[39px] font-bold">
                                ${finalPrice.toFixed(2)}
                            </span>
                            {promoApplied && finalPrice < selectedVariant.price && (
                                <>
                                    <span className="text-[#0000004D] line-through text-[24px] md:text-[28px] leading-[34px] font-medium">
                                        ${selectedVariant.price.toFixed(2)}
                                    </span>
                                    <Badge className="bg-[#00C92C1A] text-[#00C92C] border-0 hover:bg-[#00C92C1A] rounded-full text-[14px] leading-[20px] font-medium px-3 py-1">
                                        {discountData?.type === 'percentage' 
                                            ? `-${discountData.value}%` 
                                            : `-$${discountData?.value}`} {t.discountBadge}
                                    </Badge>
                                </>
                            )}
                            {!promoApplied && discountPercentage > 0 && (
                                <>
                                    <span className="text-[#0000004D] line-through text-[28px] md:text-[32px] leading-[39px] font-bold">
                                        ${product.base_price.toFixed(2)}
                                    </span>
                                    <Badge className="bg-[#FF33331A] text-[#FF3333] border-0 hover:bg-[#FF33331A] rounded-full text-[16px] leading-[22px] font-medium px-3.5 py-1.5">
                                        -{discountPercentage}%
                                    </Badge>
                                </>
                            )}
                        </div>

                        <p className="mt-4 sm:mt-6 text-[#00000099] text-[16px] leading-5 font-normal max-w-[600px]">
                            {product.description}
                        </p>

                        <Separator className="my-4 sm:my-6" />

                        {/* Colors */}
                        {colors.length > 0 && (
                            <>
                                <div>
                                    <TypographyH4 className="text-[#00000099] text-[16px] leading-[11px] font-normal mb-3 sm:mb-4">
                                        {t.selectColors}
                                    </TypographyH4>
                                    <div className="flex items-center gap-4">
                                        {colors.map((c) => (
                                            <button
                                                key={c.id}
                                                onClick={() => setSelectedColor(c.name)}
                                                aria-label={c.name}
                                                className={`relative cursor-pointer flex items-center justify-center h-[37px] w-[37px] rounded-full transition ${selectedColor === c.name ? "" : ""}`}
                                                style={{ backgroundColor: c.hex }}
                                            >
                                                {selectedColor === c.name ? (
                                                    <Image src='/assets/icons/checkmark.svg' alt="checkmark" width={16} height={16} />
                                                ) : null}
                                            </button>
                                        ))}
                                    </div>
                                </div>
                                <Separator className="my-4 sm:my-6" />
                            </>
                        )}

                        {/* Sizes */}
                        {product.availableSizes.length > 0 && (
                            <>
                                <div>
                                    <TypographyH4 className="text-[#00000099] text-[16px] leading-[11px] font-normal mb-3 sm:mb-4">
                                        {t.chooseSize}
                                    </TypographyH4>
                                    <div className="flex flex-wrap items-center gap-3">
                                        {product.availableSizes.map((s) => {
                                            const selected = selectedSize === s;
                                            const isAvailable = ProductDetailService.isVariantAvailable(product.variants, s, selectedColor);
                                            return (
                                                <Button
                                                    key={s}
                                                    type="button"
                                                    onClick={() => setSelectedSize(s)}
                                                    disabled={!isAvailable}
                                                    variant={selected ? "default" : "outline"}
                                                    className={`${selected ? "bg-black text-white font-medium" : "bg-[#F0F0F0] text-[#00000099] font-normal"
                                                        } ${!isAvailable ? "opacity-50 cursor-not-allowed" : ""} rounded-full text-[16px] leading-5 px-6 border-none h-10 sm:h-11`}
                                                >
                                                    {s}
                                                </Button>
                                            );
                                        })}
                                    </div>
                                </div>
                                <Separator className="my-4 sm:my-6" />
                            </>
                        )}

                        {/* Stock Status */}
                        {selectedVariant.stock > 0 && (
                            <div className="mb-4">
                                <span className={`text-sm font-medium ${
                                    selectedVariant.stock < 5 ? 'text-orange-600' : 'text-green-600'
                                }`}>
                                    {selectedVariant.stock < 5 
                                        ? t.onlyLeft(selectedVariant.stock) 
                                        : t.inStock
                                    }
                                </span>
                            </div>
                        )}

                        {/* Promotion Code */}
                        <div className="mb-6">
                            <TypographyH4 className="text-[#00000099] text-[14px] leading-[18px] font-medium mb-2">
                                {t.promotionCode}
                            </TypographyH4>
                            <div className="flex items-start gap-3">
                                <div className="flex-1">
                                    <Input
                                        type="text"
                                        value={promoCode}
                                        onChange={(e) => {
                                            setPromoCode(e.target.value);
                                            setPromoError('');
                                        }}
                                        placeholder={t.enterPromo}
                                        className={`h-12 rounded-lg ${promoApplied ? 'border-green-500' : promoError ? 'border-red-500' : ''}`}
                                        disabled={promoApplied}
                                    />
                                    {promoError && (
                                        <p className="text-red-500 text-xs mt-1">{promoError}</p>
                                    )}
                                    {promoApplied && (
                                        <p className="text-green-600 text-xs mt-1 flex items-center gap-1">
                                            <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                                            </svg>
                                            {discountData?.message || 'Code applied successfully!'}
                                        </p>
                                    )}
                                </div>
                                <Button
                                    type="button"
                                    onClick={handleApplyPromoCode}
                                    disabled={promoApplied || !promoCode.trim() || promoLoading}
                                    variant="outline"
                                    className="h-12 px-6 rounded-lg border-gray-300 hover:bg-gray-50 disabled:opacity-50"
                                >
                                    {promoLoading ? (
                                        <span className="flex items-center gap-2">
                                            <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                                            </svg>
                                            {t.checking}
                                        </span>
                                    ) : promoApplied ? t.applied : t.apply}
                                </Button>
                            </div>
                        </div>

                        {/* Quantity + Add to Cart */}
                        <div className="flex items-center gap-3 sm:gap-5">
                            <div className="flex items-center justify-between px-4 sm:px-5 h-12 sm:h-[52px] gap-2 min-w-[140px] sm:min-w-[170px] bg-[#F0F0F0] rounded-full transition-all duration-200">
                                <Button
                                    type="button"
                                    variant="outline"
                                    className="bg-transparent border-none shadow-none hover:bg-transparent p-0 transition-transform duration-200 hover:scale-110 active:scale-95"
                                    onClick={() => setQty((q) => Math.max(1, q - 1))}
                                    disabled={disabledMinus}
                                >
                                    <Image src='/assets/icons/minus.svg' alt="minus" width={24} height={24} />
                                </Button>
                                <span className="text-[16px] leading-[22px] font-medium min-w-[20px] text-center transition-all duration-200">{qty}</span>
                                <Button
                                    type="button"
                                    variant="outline"
                                    className="bg-transparent border-none shadow-none hover:bg-transparent p-0 transition-transform duration-200 hover:scale-110 active:scale-95"
                                    onClick={() => setQty((q) => Math.min(selectedVariant.stock, q + 1))}
                                    disabled={qty >= selectedVariant.stock}
                                >
                                    <Image src='/assets/icons/plus.svg' alt="plus" width={24} height={24} />
                                </Button>
                            </div>

                            <Button
                                type="button"
                                onClick={handleAddToCart}
                                disabled={selectedVariant.stock === 0 || !selectedVariant.variant || isAddingToCart || justAdded}
                                className={`flex-1 rounded-full h-12 sm:h-[52px] px-8 md:px-8 text-[16px] font-medium disabled:opacity-50 transition-all duration-300 ${
                                    justAdded ? 'bg-green-500 hover:bg-green-600 scale-105' : ''
                                } ${
                                    isAddingToCart ? 'scale-95' : 'hover:scale-105'
                                }`}
                            >
                                {justAdded ? (
                                    <span className="flex items-center gap-2">
                                        <svg 
                                            className="w-5 h-5 animate-bounce" 
                                            fill="none" 
                                            stroke="currentColor" 
                                            viewBox="0 0 24 24"
                                        >
                                            <path 
                                                strokeLinecap="round" 
                                                strokeLinejoin="round" 
                                                strokeWidth={2} 
                                                d="M5 13l4 4L19 7" 
                                            />
                                        </svg>
                                        {t.addedToCart}
                                    </span>
                                ) : isAddingToCart ? (
                                    <span className="flex items-center gap-2">
                                        <svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
                                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                                        </svg>
                                        {t.adding}
                                    </span>
                                ) : selectedVariant.stock === 0 ? t.outOfStock : t.addToCart}
                            </Button>
                        </div>
                    </div>
                </div>
            </Container>
        </div>
    );
};

// Helper function to convert color names to hex values
function getColorHex(colorName: string): string {
    // If it's already a hex color (starts with #), return it as-is
    if (colorName.startsWith('#')) {
        return colorName.toUpperCase();
    }
    
    const colorMap: Record<string, string> = {
        'black': '#000000',
        'white': '#FFFFFF',
        'red': '#FF0000',
        'blue': '#0000FF',
        'green': '#008000',
        'yellow': '#FFFF00',
        'purple': '#800080',
        'pink': '#FFC0CB',
        'orange': '#FFA500',
        'gray': '#808080',
        'grey': '#808080',
        'brown': '#A52A2A',
        'beige': '#F5F5DC',
        'navy': '#31344F',
        'olive': '#4F4631',
        'charcoal': '#314F4A',
        'silver': '#C0C0C0',
        'gold': '#FFD700',
        'maroon': '#800000',
        'lime': '#00FF00',
        'teal': '#008080',
        'aqua': '#00FFFF',
        'fuchsia': '#FF00FF',
    };
    
    return colorMap[colorName.toLowerCase()] || '#808080'; // Default to gray
}

export default ProductDetails;