import React, { memo, useMemo, useState, useCallback } from "react";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import Image from "next/image";
import Link from "next/link";
import { Heart, ShoppingCart, Star } from "lucide-react";
import { useCart } from "@/context/CartContext";
import { useToast } from "@/context/ToastContext";

export interface ProductCardProps {
    id: string;
    slug?: string;
    title: string;
    price: number | string;
    oldPrice?: number | string;
    imageSrc: string;
    description?: string;
    rating?: number;
    ratingCount?: number;
    saleLabel?: string;
    variant?: "flash" | "featured";
    isFavorite?: boolean;
    onToggleFavorite?: () => void;
    className?: string;
    isLoading?: boolean;
}

// Move heavy computations outside component to avoid recreating functions
const formatPrice = (value: number | string): string => {
    const numValue = typeof value === 'string' ? parseFloat(value.replace(/[^0-9.-]+/g, '')) : value;
    return new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 2,
    }).format(numValue);
};

const getPriceNumber = (value: number | string): number => {
    return typeof value === 'string' ? parseFloat(value.replace(/[^0-9.-]+/g, '')) : value;
};

const getDiscountPercentage = (price: number | string, oldPrice?: number | string): number | null => {
    if (!oldPrice) return null;
    const oldPriceNum = getPriceNumber(oldPrice);
    const currentPriceNum = getPriceNumber(price);
    return Math.round(((oldPriceNum - currentPriceNum) / oldPriceNum) * 100);
};

// Simplified star rating component
const StarRating = memo(({ rating, count }: { rating: number; count: number }) => {
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 >= 0.5;
    
    return (
        <div className="flex items-center gap-2">
            <div className="flex items-center">
                {Array.from({ length: 5 }).map((_, i) => (
                    <Star
                        key={i}
                        className={`w-4 h-4 ${
                            i < fullStars || (i === fullStars && hasHalfStar)
                                ? "fill-yellow-400 text-yellow-400"
                                : "text-gray-300"
                        }`}
                    />
                ))}
            </div>
            <span className="text-sm text-gray-600">({count.toLocaleString()})</span>
        </div>
    );
});

StarRating.displayName = 'StarRating';

const ProductCard: React.FC<ProductCardProps> = memo(({
    id,
    slug,
    title,
    price,
    oldPrice,
    imageSrc,
    description = "",
    rating = 0,
    ratingCount = 0,
    saleLabel,
    variant = "featured",
    isFavorite = false,
    onToggleFavorite,
    className = "",
    isLoading = false,
}) => {
    const { addToCart } = useCart();
    const { showToast } = useToast();
    const [isAddingToCart, setIsAddingToCart] = useState(false);
    const [imageError, setImageError] = useState(false);
    const [justAdded, setJustAdded] = useState(false);

    // Memoize only essential computations
    const formattedPrice = useMemo(() => formatPrice(price), [price]);
    const formattedOldPrice = useMemo(() => oldPrice ? formatPrice(oldPrice) : null, [oldPrice]);
    const discountPercentage = useMemo(() => getDiscountPercentage(price, oldPrice), [price, oldPrice]);
    const productUrl = useMemo(() => slug ? `/products/${slug}` : `/products/${id}`, [slug, id]);

    // Optimize cart handler
    const handleAddToCart = useCallback(async () => {
        if (!id || isAddingToCart) return;

        setIsAddingToCart(true);
        
        try {
            await addToCart({
                id,
                title,
                price: getPriceNumber(price),
                imageSrc,
                slug,
            });
            
            // Trigger success animation
            setJustAdded(true);
            setTimeout(() => setJustAdded(false), 1000);
            
            showToast({
                type: 'success',
                title: 'Added to Cart',
                description: `${title} 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);
        }
    }, [id, title, price, imageSrc, slug, isAddingToCart, addToCart, showToast]);

    const handleImageError = useCallback(() => setImageError(true), []);
    
    const handleWishlistToggle = useCallback((e: React.MouseEvent) => {
        e.preventDefault();
        e.stopPropagation();
        onToggleFavorite?.();
    }, [onToggleFavorite]);

    if (isLoading) {
        return (
            <Card className={`w-full shadow-none bg-none animate-pulse ${className}`}>
                <div className="space-y-4">
                    <div className="bg-gray-200 rounded-lg h-[350px]" />
                    <div className="space-y-2">
                        <div className="h-4 bg-gray-200 rounded w-3/4" />
                        <div className="h-4 bg-gray-200 rounded w-1/2" />
                        <div className="h-10 bg-gray-200 rounded" />
                    </div>
                </div>
            </Card>
        );
    }

    return (
        <Card className={`w-full shadow-none transition-transform hover:scale-[1.02] ${className}`}>
            <div className="relative group">
                {/* Wishlist button for featured variant */}
                {variant === "featured" && onToggleFavorite && (
                    <button
                        onClick={handleWishlistToggle}
                        className="absolute right-3 top-3 z-20 p-2 rounded-full bg-white shadow-md hover:bg-gray-50 transition-colors"
                        aria-label={isFavorite ? "Remove from wishlist" : "Add to wishlist"}
                    >
                        <Heart className={`w-5 h-5 ${isFavorite ? "fill-red-500 text-red-500" : "text-gray-600"}`} />
                    </button>
                )}

                {/* Sale label for flash variant */}
                {variant === "flash" && saleLabel && (
                    <div className="absolute right-3 top-3 z-20 bg-red-500 text-white px-2 py-1 rounded text-sm font-bold">
                        {saleLabel}
                    </div>
                )}

                {/* Discount badge */}
                {discountPercentage && (
                    <div className="absolute left-3 top-3 z-20 bg-red-500 text-white px-2 py-1 rounded text-sm font-bold">
                        -{discountPercentage}%
                    </div>
                )}

                {/* Product image */}
                <div className="bg-gray-100 rounded-lg h-[300px] relative overflow-hidden group-hover:bg-gray-200 transition-colors">
                    <Link href={productUrl} className="block h-full">
                        {!imageError ? (
                            imageSrc.startsWith('data:image') ? (
                                // Use regular img tag for base64 images
                                <img 
                                    src={imageSrc} 
                                    alt={title} 
                                    className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                                    loading="lazy"
                                    onError={handleImageError}
                                />
                            ) : (
                                // Use Next.js Image component for URLs
                                <Image 
                                    src={imageSrc} 
                                    alt={title} 
                                    fill 
                                    className="object-cover group-hover:scale-105 transition-transform duration-300"
                                    loading="lazy"
                                    sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 25vw"
                                    onError={handleImageError}
                                    quality={75}
                                />
                            )
                        ) : (
                            <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                                <span className="text-gray-500 text-sm">Image unavailable</span>
                            </div>
                        )}
                    </Link>
                </div>

                {/* Flash variant pricing in image area */}
                {variant === "flash" && (
                    <div className="absolute bottom-4 left-4 right-4 bg-white/90 backdrop-blur-sm rounded-lg p-2">
                        <div className="flex items-center justify-center gap-2">
                            <span className="text-xl font-bold text-black">{formattedPrice}</span>
                            {formattedOldPrice && (
                                <span className="text-sm text-gray-500 line-through">{formattedOldPrice}</span>
                            )}
                        </div>
                    </div>
                )}
            </div>

            {/* Product details */}
            <div className="p-4 space-y-3">
                {/* Title and price for featured variant */}
                {variant === "featured" && (
                    <div className="flex items-start justify-between gap-2">
                        <Link href={productUrl} className="flex-1 min-w-0">
                            <h3 className="font-bold text-lg text-gray-900 truncate hover:text-blue-600 transition-colors">
                                {title}
                            </h3>
                        </Link>
                        <div className="text-right">
                            <div className="font-bold text-lg text-gray-900">{formattedPrice}</div>
                            {formattedOldPrice && (
                                <div className="text-sm text-gray-500 line-through">{formattedOldPrice}</div>
                            )}
                        </div>
                    </div>
                )}
                
                {/* Title for flash variant */}
                {variant === "flash" && (
                    <Link href={productUrl}>
                        <h3 className="font-bold text-lg text-gray-900 hover:text-blue-600 transition-colors line-clamp-2">
                            {title}
                        </h3>
                    </Link>
                )}
                
                {/* Description */}
                {description && (
                    <p className="text-gray-600 text-sm line-clamp-2">{description}</p>
                )}

                {/* Rating */}
                {rating > 0 && <StarRating rating={rating} count={ratingCount} />}

                {/* Add to cart button */}
                <Button 
                    variant="outline" 
                    onClick={handleAddToCart}
                    disabled={isAddingToCart || !id || justAdded}
                    className={`w-full rounded-full border-gray-900 hover:bg-gray-900 hover:text-white transition-all duration-300 ${
                        justAdded ? 'bg-green-500 border-green-500 text-white scale-105' : ''
                    } ${
                        isAddingToCart ? 'scale-95' : 'hover:scale-105'
                    }`}
                >
                    {justAdded ? (
                        <>
                            <svg 
                                className="w-5 h-5 mr-2 animate-bounce" 
                                fill="none" 
                                stroke="currentColor" 
                                viewBox="0 0 24 24"
                            >
                                <path 
                                    strokeLinecap="round" 
                                    strokeLinejoin="round" 
                                    strokeWidth={2} 
                                    d="M5 13l4 4L19 7" 
                                />
                            </svg>
                            Added!
                        </>
                    ) : (
                        <>
                            <ShoppingCart className={`w-4 h-4 mr-2 transition-transform duration-300 ${
                                isAddingToCart ? 'animate-pulse' : ''
                            }`} />
                            {isAddingToCart ? "Adding..." : "اضف إلى السلة"}
                        </>
                    )}
                </Button>
            </div>
        </Card>
    );
});

ProductCard.displayName = 'ProductCard';

export default ProductCard;

/**
 * ProductCard Component Improvements:
 * 
 * 1. Enhanced TypeScript types with better prop validation
 * 2. Improved price formatting with Intl.NumberFormat
 * 3. Better error handling for cart operations and image loading
 * 4. Enhanced accessibility with proper ARIA labels and keyboard navigation
 * 5. Modern star rating system with half-star support using Lucide icons
 * 6. Loading states for both the component and add-to-cart action
 * 7. Image error handling with fallback display
 * 8. Discount percentage calculation and display
 * 9. Better responsive design and hover states
 * 10. Memoized computations for performance optimization
 * 11. Enhanced visual feedback and transitions
 * 12. Better shopping cart integration with loading states
 * 13. Improved price display with old price support
 * 14. Consistent currency formatting
 * 15. Better component composition and maintainability
 */