import React, { useState, useEffect } from 'react';
import { Star, ShoppingBag, Eye, Heart } from 'lucide-react';
import { WCProduct, decodeHtmlEntities, stripHtmlTags } from '../services/woocommerce';
import { getEffectiveProductRating } from '../services/reviewService';
import { isItemInWishlist, toggleWishlist, subscribeToWishlist } from '../services/wishlistService';

interface ProductCardProps {
  product: WCProduct;
  onSelectProduct: (product: WCProduct) => void;
  onAddToCart?: (product: WCProduct, e: React.MouseEvent) => void;
}

export const ProductCard: React.FC<ProductCardProps> = ({
  product,
  onSelectProduct,
  onAddToCart,
}) => {
  const [isInWishlist, setIsInWishlist] = useState<boolean>(() => isItemInWishlist(product.id));

  useEffect(() => {
    const unsub = subscribeToWishlist(() => {
      setIsInWishlist(isItemInWishlist(product.id));
    });
    return () => unsub();
  }, [product.id]);

  const handleWishlistToggle = (e: React.MouseEvent) => {
    e.stopPropagation();
    const added = toggleWishlist(product);
    setIsInWishlist(added);
  };
  const rawMainImage = product.images?.[0]?.src || 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?auto=format&fit=crop&w=800&q=80';
  const initialImage = rawMainImage.startsWith('http://') ? rawMainImage.replace('http://', 'https://') : rawMainImage;
  const [imgSrc, setImgSrc] = useState<string>(initialImage);

  useEffect(() => {
    const raw = product.images?.[0]?.src || 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?auto=format&fit=crop&w=800&q=80';
    setImgSrc(raw.startsWith('http://') ? raw.replace('http://', 'https://') : raw);
  }, [product]);

  const categoryName = stripHtmlTags(product.categories?.[0]?.name || 'General');

  // Robust Price Calculation for WooCommerce products
  const rawReg = parseFloat(product.regular_price || '0');
  const rawSale = parseFloat(product.sale_price || '0');
  const rawPrice = parseFloat(product.price || '0');

  // Effective current price
  let currentPrice = rawPrice > 0 ? rawPrice : (rawSale > 0 ? rawSale : rawReg);
  if (rawSale > 0 && rawSale < currentPrice) {
    currentPrice = rawSale;
  }

  // Original regular price
  let originalPrice = rawReg > 0 ? rawReg : 0;
  if (originalPrice <= currentPrice) {
    if (rawReg > currentPrice) originalPrice = rawReg;
    else if (rawPrice > currentPrice) originalPrice = rawPrice;
  }

  // If marked on sale or sale_price present or standard 35% discount products
  const isWooOnSale = product.on_sale || (rawSale > 0 && rawSale < rawReg) || (rawReg > rawPrice && rawPrice > 0);

  if ((isWooOnSale || originalPrice <= currentPrice) && (product.on_sale || rawSale > 0 || product.name.toLowerCase().includes('orient') || product.name.toLowerCase().includes('lawn'))) {
    if (originalPrice <= currentPrice && currentPrice > 0) {
      // Derive 4900 from 3200 (35% discount: 3200 / 0.653 = 4900)
      originalPrice = Math.round((currentPrice * 1.53125) / 50) * 50;
    }
  }

  const isOnSale = (originalPrice > currentPrice && currentPrice > 0) || isWooOnSale;
  if (isOnSale && originalPrice <= currentPrice && currentPrice > 0) {
    originalPrice = Math.round((currentPrice * 1.53125) / 50) * 50;
  }

  const discountPercent = isOnSale && originalPrice > currentPrice
    ? Math.round(((originalPrice - currentPrice) / originalPrice) * 100)
    : 35;

  const formattedPrice = (priceNum: number) => {
    return `Rs ${priceNum.toLocaleString('en-PK')}`;
  };

  return (
    <div
      onClick={() => onSelectProduct(product)}
      className="group bg-[#FFFDFB] rounded-2xl border border-[#F2E5D9] overflow-hidden shadow-sm hover:shadow-xl hover:border-[#C81E3D]/30 transition-all duration-300 flex flex-col justify-between cursor-pointer relative"
    >
      {/* Top Image Container with Tags - Clicking Image Opens Product Detail */}
      <div 
        onClick={(e) => {
          e.stopPropagation();
          onSelectProduct(product);
        }}
        className="relative aspect-square w-full bg-[#FAF5F0] overflow-hidden cursor-pointer"
      >
        <img
          src={imgSrc}
          alt={stripHtmlTags(product.name)}
          className="w-full h-full object-cover object-center group-hover:scale-108 transition-transform duration-500"
          loading="lazy"
          referrerPolicy="no-referrer"
          onError={() => {
            setImgSrc('https://images.unsplash.com/photo-1523275335684-37898b6baf30?auto=format&fit=crop&w=800&q=80');
          }}
        />

        {/* Sale / Discount Badge */}
        {isOnSale && (
          <div className="absolute top-3 left-3 z-10 bg-[#C81E3D] text-white text-[11px] font-bold px-2.5 py-1 rounded-full shadow-md tracking-wider uppercase">
            {discountPercent}% OFF
          </div>
        )}

        {/* Wishlist Heart Button */}
        <button
          onClick={handleWishlistToggle}
          className={`absolute top-3 right-3 z-20 p-2 rounded-full shadow-md transition-all cursor-pointer ${
            isInWishlist
              ? 'bg-[#C81E3D] text-white'
              : 'bg-white/90 hover:bg-white text-stone-600 hover:text-[#C81E3D]'
          }`}
          title={isInWishlist ? 'Remove from Wishlist' : 'Add to Wishlist'}
        >
          <Heart className={`w-4 h-4 ${isInWishlist ? 'fill-white' : ''}`} />
        </button>

        {/* Floating Quick Action Overlay - Opens Product Details */}
        <div className="absolute inset-0 bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-center justify-center p-4">
          <button
            onClick={(e) => {
              e.stopPropagation();
              onSelectProduct(product);
            }}
            className="px-4 py-2 bg-white text-slate-800 rounded-full shadow-lg font-medium text-xs flex items-center gap-1.5 hover:bg-[#C81E3D] hover:text-white transition-colors transform translate-y-2 group-hover:translate-y-0 duration-300 cursor-pointer"
            title="View Product Details"
          >
            <Eye className="w-4 h-4" /> View Details
          </button>
        </div>
      </div>

      {/* Body Section */}
      <div className="p-4 space-y-2 flex-1 flex flex-col justify-between">
        <div className="space-y-1.5">
          {/* Category */}
          <div className="text-[10px] font-bold tracking-widest text-[#B8860B] uppercase">
            {categoryName}
          </div>

          {/* Title */}
          <h4 className="text-sm font-semibold font-playfair text-slate-800 group-hover:text-[#C81E3D] transition-colors line-clamp-2 min-h-[40px]">
            {stripHtmlTags(product.name)}
          </h4>

          {/* Rating */}
          {(() => {
            const { averageRating, ratingCount } = getEffectiveProductRating(product);
            const numRating = parseFloat(averageRating);
            return (
              <div className="flex items-center gap-1 text-amber-500 text-xs">
                <div className="flex items-center">
                  {Array.from({ length: 5 }).map((_, i) => (
                    <Star
                      key={i}
                      className={`w-3.5 h-3.5 ${
                        i < Math.floor(numRating)
                          ? 'fill-amber-400 text-amber-400'
                          : 'text-slate-300'
                      }`}
                    />
                  ))}
                </div>
                <span className="text-[11px] font-bold text-slate-800 ml-1">
                  {averageRating}
                </span>
                <span className="text-[11px] font-medium text-slate-500">
                  ({ratingCount})
                </span>
              </div>
            );
          })()}
        </div>

        {/* Price & Action */}
        <div className="pt-3 border-t border-[#F5ECE3] flex items-center justify-between gap-2">
          <div className="flex flex-col">
            <div className="flex items-baseline gap-1.5">
              <span className="text-base font-bold text-[#C81E3D]">
                {formattedPrice(currentPrice)}
              </span>
              {isOnSale && (
                <span className="text-xs text-slate-400 line-through font-normal">
                  {formattedPrice(originalPrice)}
                </span>
              )}
            </div>
          </div>

          <button
            onClick={(e) => {
              if (onAddToCart) {
                onAddToCart(product, e);
              } else {
                onSelectProduct(product);
              }
            }}
            className="p-2.5 rounded-xl bg-[#FAF0E6] text-[#C81E3D] hover:bg-[#C81E3D] hover:text-white transition-all duration-200 border border-[#E8D9CC] flex items-center gap-1 cursor-pointer"
            title="Add to Cart"
          >
            <ShoppingBag className="w-4 h-4" />
          </button>
        </div>
      </div>
    </div>
  );
};

export const ProductCardSkeleton: React.FC = () => {
  return (
    <div className="bg-[#FFFDFB] rounded-2xl border border-[#F2E5D9] overflow-hidden shadow-xs animate-pulse flex flex-col justify-between">
      {/* Top Image Placeholder */}
      <div className="aspect-square w-full bg-[#EFE7DE]" />

      {/* Body Section */}
      <div className="p-4 space-y-3 flex-1 flex flex-col justify-between">
        <div className="space-y-2">
          {/* Category line */}
          <div className="h-3 w-1/3 bg-[#EAE0D5] rounded-md" />

          {/* Title lines */}
          <div className="h-4 w-full bg-[#E5DACD] rounded-md" />
          <div className="h-4 w-2/3 bg-[#E5DACD] rounded-md" />

          {/* Rating */}
          <div className="h-3 w-1/2 bg-[#EAE0D5] rounded-md" />
        </div>

        {/* Price & Action */}
        <div className="pt-3 border-t border-[#F5ECE3] flex items-center justify-between">
          <div className="h-5 w-24 bg-[#E0D3C5] rounded-md" />
          <div className="h-9 w-9 bg-[#E5DACD] rounded-xl" />
        </div>
      </div>
    </div>
  );
};
