import React, { useState } from "react";
import { Product } from "../types";
import NoImagePlaceholder from "./NoImagePlaceholder";

interface RelatedProductCardProps {
  product: Product;
  onAddToCart: (product: Product) => void;
  onClick?: () => void;
}

/**
 * RelatedProductCard Component
 * Componente reutilizável para exibir cards de produtos relacionados (Compre Junto / Similares)
 * 
 * @param product - Dados do produto
 * @param onAddToCart - Callback para adicionar ao carrinho
 * @param onClick - Callback quando o card é clicado (opcional)
 */
const RelatedProductCard: React.FC<RelatedProductCardProps> = ({
  product,
  onAddToCart,
  onClick,
}) => {
  const [imageError, setImageError] = useState(false);

  return (
    <div
      className="bg-white border border-slate-200 rounded-2xl p-4 hover:shadow-lg transition-all cursor-pointer group"
      onClick={onClick}
    >
      <div className="h-32 bg-slate-50 rounded-xl mb-3 flex items-center justify-center overflow-hidden">
        {product.image && !product.image.includes("placeholder") && !imageError ? (
          <img
            src={product.image}
            alt={product.name}
            className="max-h-full max-w-full object-contain group-hover:scale-110 transition-transform"
            onError={() => setImageError(true)}
          />
        ) : (
          <NoImagePlaceholder size="sm" />
        )}
      </div>
      <h4 className="text-sm font-bold text-[#002147] mb-2 line-clamp-2">
        {product.name}
      </h4>
      <p className="text-lg font-black text-orange-600 mb-3">
        R${" "}
        {product.price.toLocaleString("pt-BR", {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        })}
      </p>
      <button
        onClick={(e) => {
          e.stopPropagation();
          // Ao clicar em "Adicionar", abre o modal de detalhes do produto
          // (mesmo comportamento do Angular portal)
          if (onClick) {
            onClick();
          } else {
            // Fallback: se não houver onClick, adiciona diretamente ao carrinho
            onAddToCart({ ...product, quantity: 1 });
          }
        }}
        className="w-full bg-[#002147] text-white py-2 rounded-lg text-xs font-bold uppercase tracking-wide hover:bg-[#003366] transition-all"
      >
        Adicionar
      </button>
    </div>
  );
};

export default RelatedProductCard;


