'use client';

import Link from 'next/link';
import { useCartStore, useWishlistStore, useToastStore } from '@/lib/store';
import type { Product } from '@/lib/types';
import AuctionCountdown from '@/components/product/AuctionCountdown';

const badgeColors: Record<string, string> = {
  'Best Seller': 'bg-blue-600',
  'Sale': 'bg-red-500',
  'New': 'bg-green-500',
  'Hot': 'bg-orange-500',
  'Deal': 'bg-purple-500',
};

function StarRating({ rating }: { rating: number }) {
  const full = Math.floor(rating);
  const half = rating % 1 >= 0.5;
  return (
    <div className="flex items-center gap-0.5">
      {Array.from({ length: 5 }, (_, i) => (
        <svg key={i} className={`w-4 h-4 ${i < full ? 'text-yellow-400' : (i === full && half ? 'text-yellow-400' : 'text-gray-300')} fill-current`} 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>
      ))}
    </div>
  );
}

export default function ProductCard({ product }: { product: Product }) {
  const addToCart = useCartStore(s => s.addItem);
  const wishlistToggle = useWishlistStore(s => s.toggle);
  const wishlistHas = useWishlistStore(s => s.has);
  const toast = useToastStore(s => s.show);
  const isWished = wishlistHas(product.id);

  const discount = product.original_price > product.price
    ? Math.round((1 - product.price / product.original_price) * 100)
    : 0;

  function handleAddToCart() {
    addToCart(product);
    toast(`${product.name.substring(0, 30)}... added to cart`, 'success');
  }

  function handleWishlistToggle() {
    wishlistToggle(product.id);
    toast(isWished ? 'Removed from wishlist' : 'Added to wishlist', isWished ? 'info' : 'success');
  }

  return (
    <div className="product-card bg-white rounded-2xl shadow-md hover:shadow-xl transition-all duration-300 overflow-hidden group relative flex flex-col">
      <div className="relative overflow-hidden bg-gray-50">
        <Link href={`/products/${product.id}`}>
          <img src={product.image_url} alt={product.name} className="w-full h-52 object-cover group-hover:scale-105 transition-transform duration-500" />
        </Link>
        {product.badge && (
          <span className={`absolute top-3 left-3 text-xs font-bold text-white px-2.5 py-1 rounded-full ${badgeColors[product.badge] || 'bg-blue-600'}`}>{product.badge}</span>
        )}
        {discount > 0 && (
          <span className="absolute top-3 right-10 text-xs font-bold text-white bg-red-500 px-2 py-1 rounded-full">-{discount}%</span>
        )}
        <button onClick={handleWishlistToggle} className={`absolute top-3 right-3 w-8 h-8 bg-white rounded-full shadow flex items-center justify-center ${isWished ? 'text-red-500' : 'text-gray-400'} hover:text-red-500 transition-colors`}>
          <svg className="w-4 h-4 fill-current" viewBox="0 0 20 20"><path d="M3.172 5.172a4 4 0 015.656 0L10 6.343l1.172-1.171a4 4 0 115.656 5.656L10 17.657l-6.828-6.829a4 4 0 010-5.656z"/></svg>
        </button>
        {/* Auction overlay */}
        {product.is_auction && product.auction_end_time && (
          <div className="absolute bottom-0 left-0 right-0">
            <AuctionCountdown endTime={product.auction_end_time} productId={product.id} compact />
          </div>
        )}
      </div>
      <div className="p-4 flex flex-col flex-1">
        <p className="text-xs text-blue-600 font-semibold uppercase tracking-wide mb-1">{product.brand}</p>
        <Link href={`/products/${product.id}`} className="text-sm font-semibold text-gray-800 hover:text-blue-700 line-clamp-2 mb-2 flex-1">{product.name}</Link>
        <div className="flex items-center gap-1 mb-2">
          <StarRating rating={product.rating} />
          <span className="text-xs text-gray-500 ml-1">({product.reviews_count.toLocaleString()})</span>
        </div>
        <div className="flex items-center gap-2 mb-1">
          <span className="text-lg font-bold text-gray-900">${product.price.toFixed(2)}</span>
          {product.original_price > product.price && (
            <span className="text-sm text-gray-400 line-through">${product.original_price.toFixed(2)}</span>
          )}
        </div>
        {/* Payvato badge */}
        {product.payvato_eligible && (
          <p className="text-xs text-emerald-600 font-semibold mb-2">
            💳 From ${(product.price / 12).toFixed(2)}/mo with Payvato
          </p>
        )}
        <button onClick={handleAddToCart} className="w-full bg-yellow-400 hover:bg-yellow-500 text-gray-900 font-bold py-2 px-4 rounded-xl transition-colors duration-200 text-sm flex items-center justify-center gap-2">
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
          {product.is_auction ? 'Place Bid' : 'Add to Cart'}
        </button>
      </div>
    </div>
  );
}

export { StarRating };
