import { Link } from '@tanstack/react-router';
import { ShoppingCart, FlaskConical } from 'lucide-react';
import StarRating from '@/components/StarRating';
import AddToCartButton from '@/components/AddToCartButton';
import { useGqlCart } from '@/hooks/useGqlCart';
import { useCartDrawerStore } from '@/stores/cartDrawerStore';
import type { Product } from '@/data/mockProducts';
import { findLabTestForProduct } from '@/data/labTests';
import { toast } from 'sonner';
import { useT } from '@/lib/i18n';

const ProductCard = ({ product }: { product: Product }) => {
  const t = useT();
  const { addItem } = useGqlCart();
  const openCart = useCartDrawerStore((s) => s.open);
  const labTest = findLabTestForProduct(product.name, product.slug);

  const isVariable = product.type === 'variable' || (product.variations && product.variations.length > 0);

  // Variable products require a variation choice, so the card sends the shopper
  // to the product page instead of adding a line that is not valid yet.
  const handleChooseOptions = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    window.location.href = `${window.location.pathname.startsWith('/en') ? '/en' : ''}/product/${product.slug}`;
  };

  const handleAdd = async () => {
    try {
      await addItem({ productId: product.id, quantity: 1 });
      openCart();
    } catch (err) {
      console.error('addToCart failed', err);
      const isBundle = String((err as Error)?.message || '').includes('woosb');
      toast.error(
        isBundle
          ? t('Deze bundel kan momenteel niet online worden toegevoegd.', 'This bundle cannot be added online right now.')
          : t('Kon product niet aan winkelwagen toevoegen.', 'Could not add product to cart.'),
      );
      // Rethrow so the button returns to its resting state instead of claiming success.
      throw err;
    }
  };

  return (
    <Link
      to="/product/$slug"
      params={{ slug: product.slug }}
      className="group relative glass-card-premium overflow-hidden flex flex-col focus-ring"
    >
      <div className="relative aspect-square bg-gradient-to-br from-surface/80 to-surface-alt/40 overflow-hidden">
        <img src={product.image} alt={`${product.name} — ${t('research peptide vial kopen bij Peptidewinkel', 'buy research peptide vial at Peptidewinkel')}`} loading="lazy" decoding="async" width={400} height={400} className="w-full h-full object-contain p-6 group-hover:scale-110 transition-transform duration-500" />
        <div className="absolute top-3 left-3 flex flex-col gap-1.5 z-10">
          {product.salePrice && (
            <span className="bg-destructive text-destructive-foreground text-xs font-bold px-2.5 py-1 rounded-lg shadow-elevated">
              -{Math.round((1 - product.salePrice / product.price) * 100)}%
            </span>
          )}
          {product.isNew && (
            <span className="gradient-primary text-white text-xs font-bold px-2.5 py-1 rounded-lg shadow-elevated">{t('Nieuw', 'New')}</span>
          )}
          {labTest && (
            <span className="bg-primary/95 text-primary-foreground text-[10px] font-bold px-2 py-0.5 rounded-lg shadow-elevated flex items-center gap-1">
              <FlaskConical className="w-3 h-3" /> {t('Labgetest', 'Lab tested')}
            </span>
          )}
        </div>
        {product.inStock && (
          <div className="absolute inset-x-0 bottom-0 p-3 translate-y-full group-hover:translate-y-0 focus-within:translate-y-0 transition-transform duration-300 z-10">
            {isVariable ? (
              <button
                type="button"
                onClick={handleChooseOptions}
                aria-label={`${t('Bekijk opties voor', 'View options for')} ${product.name}`}
                className="w-full py-2.5 rounded-xl gradient-primary text-white text-xs font-bold flex items-center justify-center gap-2 shadow-glow-soft hover:opacity-95 transition-opacity focus-ring"
              >
                <ShoppingCart className="w-3.5 h-3.5" aria-hidden="true" />
                {t('Kies opties', 'Choose options')}
              </button>
            ) : (
              <AddToCartButton
                size="compact"
                onAdd={handleAdd}
                label={t('Toevoegen', 'Add to cart')}
                pendingLabel={t('Toevoegen…', 'Adding…')}
                addedLabel={t('Toegevoegd', 'Added')}
                aria-label={`${t('Voeg', 'Add')} ${product.name} ${t('toe aan winkelwagen', 'to cart')}`}
                className="shadow-glow-soft focus-ring"
              />
            )}
          </div>
        )}
        {!product.inStock && (
          <div className="absolute inset-0 bg-background/60 backdrop-blur-sm flex items-center justify-center z-10">
            <span className="bg-muted text-muted-foreground font-semibold text-sm px-4 py-1.5 rounded-xl">{t('Uitverkocht', 'Out of stock')}</span>
          </div>
        )}
      </div>

      <div className="p-5 flex flex-col flex-1 relative">
        <p className="text-[10px] text-primary font-bold mb-1.5 uppercase tracking-[0.2em]">{product.category}</p>
        <h3 className="font-display font-bold text-[15px] leading-snug mb-2.5 group-hover:text-primary transition-colors tracking-tight">{product.name}</h3>

        <div
          className="flex items-center gap-1 mb-3"
          aria-label={`${t('Beoordeling:', 'Rating:')} ${product.rating.toFixed(1)} ${t('van 5 sterren, gebaseerd op', 'out of 5 stars, based on')} ${product.reviewCount} ${t('reviews', 'reviews')}`}
        >
          <StarRating rating={product.rating} sizeClass="w-3.5 h-3.5" />
          <span className="text-xs text-muted-foreground ml-1" aria-hidden="true">({product.reviewCount})</span>
        </div>

        <div className="mt-auto pt-3 border-t border-border/60 flex items-end justify-between gap-2">
          <div>
            {product.salePrice ? (
              <div className="flex items-baseline gap-2">
                <span className="font-display font-extrabold text-xl text-gradient-primary tracking-tighter">€{product.salePrice.toFixed(2)}</span>
                <span className="text-sm text-muted-foreground line-through">€{product.price.toFixed(2)}</span>
              </div>
            ) : (
              <span className="font-display font-extrabold text-xl tracking-tighter text-primary">€{product.price.toFixed(2)}</span>
            )}
          </div>
        </div>
      </div>

    </Link>
  );
};

export default ProductCard;
