'use client';

import { useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { ShopwareProduct, getProductUrl } from '@/lib/shopware-api';
import WishlistButton from '@/components/product/WishlistButton';
import { useCart } from '@/lib/cart-context';
import { useTranslation } from '@/lib/i18n-context';
import { useSalesChannel } from '@/lib/sales-channel-context';

interface ProductCardProps {
  product: ShopwareProduct;
  categoryId?: string;
}

export default function ProductCard({ product, categoryId }: ProductCardProps) {
  const name = product.translated?.name || product.name;
  const price = product.calculatedPrice?.unitPrice || product.price?.[0]?.gross || 0;
  const listPrice = product.calculatedPrice?.listPrice?.price;
  const imageUrl = product.cover?.media?.url;
  const hasDiscount = listPrice && listPrice > price;
  const { localizeHref, formatPrice } = useSalesChannel();
  const href = localizeHref(getProductUrl(product, categoryId));

  const { addToCart } = useCart();
  const { t } = useTranslation();
  const [adding, setAdding] = useState(false);
  const [added, setAdded] = useState(false);

  const handleAddToCart = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (adding) return;
    setAdding(true);
    try {
      await addToCart(product.id, 1);
      setAdded(true);
      setTimeout(() => setAdded(false), 2000);
    } catch {
      // ignore
    } finally {
      setAdding(false);
    }
  };

  return (
    <div className="group relative flex flex-col h-full">
      <Link href={href} className="flex flex-col flex-1">
        <div className="relative bg-surface-50 rounded-xl overflow-hidden aspect-square mb-3">
          {imageUrl ? (
            <Image
              src={imageUrl}
              alt={name}
              fill
              sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"
              className="object-contain p-4 group-hover:scale-105 transition-transform duration-300"
            />
          ) : (
            <div className="w-full h-full flex items-center justify-center text-surface-300 text-4xl">
              📦
            </div>
          )}

          {hasDiscount && (
            <span className="absolute top-3 left-3 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded-md">
              Sale
            </span>
          )}

          <WishlistButton productId={product.id} variant="card" />
        </div>

        <div className="flex-1 flex flex-col">
          {product.manufacturer?.name && (
            <p className="text-xs text-surface-400 mb-1">{product.manufacturer.name}</p>
          )}

          <h3 className="font-medium text-sm leading-snug group-hover:text-brand-600 transition-colors line-clamp-2">
            {name}
          </h3>

          <div className="flex items-baseline gap-2 mt-auto pt-2">
            <span className="font-bold text-lg">{formatPrice(price)}</span>
            {hasDiscount && (
              <span className="text-sm text-surface-400 line-through">
                {formatPrice(listPrice)}
              </span>
            )}
          </div>

          {product.ratingAverage && (
            <div className="flex items-center gap-1 mt-1.5">
              <svg className="w-3.5 h-3.5 text-yellow-400" fill="currentColor" viewBox="0 0 20 20">
                <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
              </svg>
              <span className="text-xs text-surface-400">{product.ratingAverage.toFixed(1)}</span>
            </div>
          )}
        </div>
      </Link>

      {price > 0 && (
        <button
          onClick={handleAddToCart}
          disabled={adding}
          className={`mt-3 w-full py-2.5 rounded-xl text-sm font-semibold transition-all ${
            added
              ? 'bg-green-500 text-white'
              : 'bg-surface-900 hover:bg-surface-700 text-white active:scale-[0.98]'
          } disabled:opacity-50`}
        >
          {adding ? (
            <span className="flex items-center justify-center gap-1.5">
              <svg className="w-4 h-4 animate-spin" viewBox="0 0 24 24" fill="none">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
              </svg>
              {t('listing.boxAddProductAdding', 'Adding...')}
            </span>
          ) : added ? (
            <span className="flex items-center justify-center gap-1.5">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
              </svg>
              {t('listing.boxAddProductAdded', 'Added!')}
            </span>
          ) : (
            <span className="flex items-center justify-center gap-1.5">
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
              </svg>
              {t('listing.boxAddProduct', 'Add to cart')}
            </span>
          )}
        </button>
      )}
    </div>
  );
}
