import { useState } from 'react'
import { Link } from 'react-router-dom'
import { formatPrice, Product } from '../api'
import { IconLeaf } from './Icons'
import OriginBadge from './OriginBadge'

export default function ProductCard({ product }: { product: Product }) {
  const [imageFailed, setImageFailed] = useState(false)
  const image = product.images.length > 0 ? product.images[0] : null
  const showImage = image !== null && !imageFailed

  return (
    <Link
      to={`/produits/${encodeURIComponent(product.uid)}`}
      className="card product-card"
    >
      <div className="product-card-media">
        {showImage ? (
          <img
            src={image}
            alt={product.title}
            loading="lazy"
            decoding="async"
            onError={() => setImageFailed(true)}
          />
        ) : (
          <div className="image-placeholder" aria-hidden="true">
            <IconLeaf size={30} />
          </div>
        )}
        <span className="product-card-badge">
          <OriginBadge origin={product.origin_class} />
        </span>
      </div>
      <div className="product-card-body">
        <h3 className="product-card-title">{product.title}</h3>
        <div className="product-card-price">
          {product.price !== null ? (
            <span className="price-chip">{formatPrice(product.price)}</span>
          ) : (
            <span className="price-chip price-chip-muted">Prix variable</span>
          )}
          {product.compare_at_price !== null &&
            product.price !== null &&
            product.compare_at_price > product.price && (
              <s className="price-compare">
                {formatPrice(product.compare_at_price)}
              </s>
            )}
        </div>
        <p className="product-card-store">
          {product.store_name}
          {product.store_region ? ` · ${product.store_region}` : ''}
        </p>
      </div>
    </Link>
  )
}
