import { useState } from 'react';
import { Heart } from 'lucide-react';

interface WishlistButtonProps {
  productId: string;
  productName: string;
  productImage: string;
  productPrice: number;
  isInWishlist?: boolean;
  size?: 'sm' | 'md' | 'lg';
  showLabel?: boolean;
}

export default function WishlistButton({
  productId,
  productName,
  productImage,
  productPrice,
  isInWishlist: initialState = false,
  size = 'md',
  showLabel = false
}: WishlistButtonProps) {
  const [isInWishlist, setIsInWishlist] = useState(initialState);
  const [isAnimating, setIsAnimating] = useState(false);

  const sizeConfig = {
    sm: { button: 'w-8 h-8', icon: 'w-4 h-4', text: 'text-xs' },
    md: { button: 'w-10 h-10', icon: 'w-5 h-5', text: 'text-sm' },
    lg: { button: 'w-12 h-12', icon: 'w-6 h-6', text: 'text-base' }
  };

  const toggleWishlist = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    
    setIsAnimating(true);
    
    try {
      if (isInWishlist) {
        // Remove from wishlist
        await fetch(`/api/wishlist/${productId}`, { method: 'DELETE' });
        setIsInWishlist(false);
      } else {
        // Add to wishlist
        await fetch('/api/wishlist', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            productId,
            productName,
            productImage,
            productPrice
          })
        });
        setIsInWishlist(true);
      }
    } catch (error) {
      console.error('Failed to update wishlist:', error);
    }
    
    setTimeout(() => setIsAnimating(false), 500);
  };

  return (
    <button
      onClick={toggleWishlist}
      className={`
        ${sizeConfig[size].button} 
        rounded-full flex items-center justify-center transition-all
        ${isInWishlist 
          ? 'bg-red-50 text-red-500 hover:bg-red-100' 
          : 'bg-white/80 backdrop-blur text-gray-400 hover:text-red-500 hover:bg-white'
        }
        ${isAnimating ? 'scale-110' : 'scale-100'}
        shadow-sm hover:shadow-md
      `}
      aria-label={isInWishlist ? 'ลบออกจากรายการโปรด' : 'เพิ่มไปยังรายการโปรด'}
    >
      <Heart
        className={`${sizeConfig[size].icon} transition-transform ${isAnimating ? 'animate-pulse' : ''}`}
        fill={isInWishlist ? 'currentColor' : 'none'}
      />
      {showLabel && (
        <span className={`ml-2 ${sizeConfig[size].text} ${isInWishlist ? 'text-red-500' : 'text-gray-600'}`}>
          {isInWishlist ? 'ในรายการโปรด' : 'เพิ่มไปรายการโปรด'}
        </span>
      )}
    </button>
  );
}
