'use client';

import { useState, useCallback } from 'react';
import { Star, Eye, Heart } from 'lucide-react';
import { Product, useCartStore } from '@/store/cart-store';

/* ── Color Name → Tailwind BG Class ────────────────────────────── */
const colorMap: Record<string, string> = {
  Black: 'bg-gray-900',
  White: 'bg-white border border-gray-200',
  Navy: 'bg-blue-900',
  Cream: 'bg-amber-100',
  Blue: 'bg-blue-500',
  Light: 'bg-sky-300',
  Pink: 'bg-pink-300',
  Gray: 'bg-gray-400',
  Green: 'bg-green-600',
  Red: 'bg-red-500',
  Maroon: 'bg-red-800',
  Olive: 'bg-olive-700',
  Khaki: 'bg-yellow-700',
  Sky: 'bg-sky-400',
  Sand: 'bg-amber-200',
  Wine: 'bg-purple-800',
  Charcoal: 'bg-gray-700',
  Camel: 'bg-amber-600',
  Beige: 'bg-amber-100',
};

interface ProductCardProps {
  product: Product;
}

export default function ProductCard({ product }: ProductCardProps) {
  const [isHovered, setIsHovered] = useState(false);
  const [addedFeedback, setAddedFeedback] = useState(false);
  const [pulsing, setPulsing] = useState(false);

  const addItem = useCartStore((s) => s.addItem);
  const openCart = useCartStore((s) => s.openCart);
  const isInWishlist = useCartStore((s) => s.isInWishlist);
  const toggleWishlist = useCartStore((s) => s.toggleWishlist);

  const wishlisted = isInWishlist(product.id);

  const handleAddToCart = useCallback(() => {
    addItem({
      ...product,
      quantity: 1,
      selectedSize: product.sizes.includes('M') ? 'M' : product.sizes[0],
      selectedColor: product.colors[0],
    });
    setAddedFeedback(true);
    openCart();
    setTimeout(() => setAddedFeedback(false), 1200);
  }, [product, addItem, openCart]);

  const handleWishlist = useCallback(() => {
    toggleWishlist(product.id);
    setPulsing(true);
    setTimeout(() => setPulsing(false), 300);
  }, [product.id, toggleWishlist]);

  const renderStars = () => {
    const stars = [];
    const fullStars = Math.floor(product.rating);
    const hasHalf = product.rating % 1 >= 0.5;
    for (let i = 0; i < 5; i++) {
      if (i < fullStars) {
        stars.push(
          <Star key={i} className="w-3 h-3 fill-amber-400 text-amber-400" />
        );
      } else if (i === fullStars && hasHalf) {
        stars.push(
          <div key={i} className="relative">
            <Star className="w-3 h-3 text-gray-300" />
            <div className="absolute inset-0 overflow-hidden w-1/2">
              <Star className="w-3 h-3 fill-amber-400 text-amber-400" />
            </div>
          </div>
        );
      } else {
        stars.push(<Star key={i} className="w-3 h-3 text-gray-300" />);
      }
    }
    return stars;
  };

  return (
    <div className="product-card bg-white rounded-2xl border border-gray-100 overflow-hidden hover:shadow-xl hover:-translate-y-1 transition-all duration-300">
      {/* ── Image Area ─────────────────────────────────────── */}
      <div
        className="relative aspect-[3/4] overflow-hidden bg-gray-100"
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
      >
        <img
          src={isHovered ? product.hoverImage : product.image}
          alt={product.name}
          className="product-card-image w-full h-full object-cover"
        />

        {/* Discount Badge */}
        <span className="absolute top-3 left-3 bg-red-500 text-white text-xs font-bold px-2.5 py-1 rounded-full">
          -{product.discount}%
        </span>

        {/* Category Badge */}
        {product.badge && (
          <span className="absolute top-3 right-3 bg-brand text-white text-[10px] font-bold px-2.5 py-1 rounded-full">
            {product.badge}
          </span>
        )}

        {/* Quick View Button */}
        <button
          className="absolute bottom-3 left-3 w-10 h-10 bg-white/90 backdrop-blur-sm rounded-full shadow-md flex items-center justify-center text-gray-700 hover:text-brand transition-colors"
          aria-label="Quick view"
        >
          <Eye className="w-4 h-4" />
        </button>

        {/* Wishlist Heart Button */}
        <button
          onClick={handleWishlist}
          className={`absolute bottom-3 right-3 w-10 h-10 bg-white/90 backdrop-blur-sm rounded-full shadow-md flex items-center justify-center transition-colors ${
            wishlisted ? 'text-red-500' : 'text-gray-700 hover:text-red-400'
          } ${pulsing ? 'animate-pulse-heart' : ''}`}
          aria-label={wishlisted ? 'Remove from wishlist' : 'Add to wishlist'}
        >
          <Heart
            className={`w-4 h-4 ${wishlisted ? 'fill-red-500' : ''}`}
          />
        </button>
      </div>

      {/* ── Body ────────────────────────────────────────────── */}
      <div className="p-3 lg:p-4">
        {/* Category Label */}
        <p className="text-[10px] text-brand font-semibold uppercase tracking-wider">
          {product.category}
        </p>

        {/* Product Name */}
        <h3 className="text-sm font-semibold text-gray-800 line-clamp-2 mt-1">
          {product.name}
        </h3>

        {/* Star Rating + Reviews */}
        <div className="flex items-center gap-1 mt-1.5">
          <div className="flex items-center gap-0.5">{renderStars()}</div>
          <span className="text-[10px] text-gray-400">({product.reviews})</span>
        </div>

        {/* Price Row */}
        <div className="flex items-center gap-2 mt-2">
          <span className="text-lg font-bold text-gray-900">
            ৳{product.price.toLocaleString()}
          </span>
          <span className="text-sm text-gray-400 line-through">
            ৳{product.originalPrice.toLocaleString()}
          </span>
        </div>

        {/* Color Swatches */}
        <div className="flex items-center gap-1.5 mt-2.5">
          {product.colors.map((color) => (
            <span
              key={color}
              className={`w-4 h-4 rounded-full ${colorMap[color] || 'bg-gray-300'}`}
              title={color}
            />
          ))}
        </div>

        {/* Add to Cart Button */}
        <button
          onClick={handleAddToCart}
          disabled={addedFeedback}
          className={`w-full py-2.5 mt-3 text-white text-xs font-semibold rounded-xl transition-all duration-300 ${
            addedFeedback
              ? 'bg-green-500 cursor-default'
              : 'bg-gray-900 hover:bg-brand'
          }`}
        >
          {addedFeedback ? '✓ Added!' : 'Add to Cart'}
        </button>
      </div>
    </div>
  );
}
