import Image from "next/image";
import { Heart, Plus } from "lucide-react";
import { type CatalogProduct, type ProductVariant, minimumPrice } from "@/data/catalog";
import { formatPrice } from "@/data/category-showcases";
import { useDemoStore } from "./demo-store";
import Link from "next/link";
import { productHref } from "@/lib/products";

export function CatalogProductCard({ product, onProduct, matchedVariant }: { product: CatalogProduct; onProduct: (id: string, variantId?: string) => void; matchedVariant?: ProductVariant }) {
  const { wishlist, toggleWish } = useDemoStore();
  const saved = wishlist.includes(product.id);
  const price = matchedVariant?.price ?? minimumPrice(product);
  const differentPrices = !matchedVariant && product.variants.some((variant) => variant.price !== price);
  return (
    <article className="catalog-product-card" data-product-id={product.id} data-price={price}>
      <div className="catalog-product-photo">
        <Link href={productHref(product.id, matchedVariant?.id)} className="catalog-image-button" aria-label={`View ${product.name}`}><Image src={matchedVariant?.images[0] ?? product.image} alt={`${product.name}${matchedVariant ? `, ${matchedVariant.color}` : ""}`} fill sizes="(max-width: 600px) 45vw, (max-width: 1100px) 30vw, 21vw" className="category-product-image" /></Link>
        {product.badge && <span className="catalog-badge">{product.badge}</span>}
        <button type="button" className={`catalog-heart ${saved ? "is-saved" : ""}`} onClick={() => toggleWish(product.id)} aria-label={`${saved ? "Remove" : "Save"} ${product.name} ${saved ? "from" : "to"} wishlist`} aria-pressed={saved}><Heart size={19} fill={saved ? "currentColor" : "none"} /></button>
        <button type="button" className="catalog-quick-add" onClick={() => onProduct(product.id, matchedVariant?.id)}>Quick add <Plus size={17} /></button>
      </div>
      <p className="catalog-product-meta">{product.group} / {product.categoryName}</p>
      <Link href={productHref(product.id, matchedVariant?.id)} className="catalog-product-name">{product.name}</Link>
      <div className="catalog-product-price"><strong>{differentPrices && <small>From </small>}{formatPrice(price)}</strong><del>{formatPrice(product.oldPrice)}</del><span>-{Math.round((1 - price / product.oldPrice) * 100)}%</span></div>
    </article>
  );
}
