"use client";

import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { Heart, ShoppingCart, Eye, Star, Zap } from "lucide-react";
import { useCartStore } from "@/store/cart";
import { formatPrice, calculateDiscount } from "@/lib/utils";
import { cn } from "@/lib/utils";
import toast from "react-hot-toast";

export interface ProductCardData {
  id: string;
  name: string;
  slug: string;
  price: number;
  comparePrice?: number | null;
  images: string[];
  stock: number;
  isNew: boolean;
  isHot: boolean;
  featured: boolean;
  condition: string;
  brand: { name: string };
  category: { name: string; slug: string };
  reviews?: { rating: number }[];
}

interface ProductCardProps {
  product: ProductCardData;
  className?: string;
}

export default function ProductCard({ product, className }: ProductCardProps) {
  const router = useRouter();
  const { addItem } = useCartStore();
  const discount = product.comparePrice
    ? calculateDiscount(product.price, Number(product.comparePrice))
    : null;

  const avgRating =
    product.reviews && product.reviews.length > 0
      ? product.reviews.reduce((s, r) => s + r.rating, 0) / product.reviews.length
      : null;

  const handleAddToCart = (e: React.MouseEvent) => {
    e.preventDefault();
    if (product.stock === 0) return;
    addItem({
      id: product.id,
      name: product.name,
      price: product.price,
      image: product.images[0] || "/images/placeholder.png",
      slug: product.slug,
      stock: product.stock,
    });
    toast.success(`${product.name.slice(0, 30)}... added to cart!`);
  };

  return (
    <Link href={`/products/${product.slug}`} className={cn("group block", className)}>
      <div className="bg-white rounded-2xl overflow-hidden border border-slate-100 hover:border-sky-200 hover:shadow-xl hover:shadow-sky-100/50 transition-all duration-300">
        {/* Image container */}
        <div className="relative aspect-[4/3] bg-slate-50 overflow-hidden">
          <Image
            src={product.images[0] || "/images/placeholder.png"}
            alt={product.name}
            fill
            className="object-cover group-hover:scale-105 transition-transform duration-500"
            sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"
          />

          {/* Badges */}
          <div className="absolute top-2 left-2 flex flex-col gap-1">
            {product.isNew && (
              <span className="bg-emerald-500 text-white text-xs font-bold px-2 py-0.5 rounded-full">NEW</span>
            )}
            {product.isHot && (
              <span className="bg-orange-500 text-white text-xs font-bold px-2 py-0.5 rounded-full flex items-center gap-0.5">
                <Zap className="w-2.5 h-2.5" /> HOT
              </span>
            )}
            {discount && discount > 0 && (
              <span className="bg-red-500 text-white text-xs font-bold px-2 py-0.5 rounded-full">
                -{discount}%
              </span>
            )}
            {product.condition !== "Brand New" && (
              <span className="bg-blue-500 text-white text-xs font-bold px-2 py-0.5 rounded-full">
                {product.condition}
              </span>
            )}
          </div>

          {/* Stock badge */}
          {product.stock === 0 && (
            <div className="absolute inset-0 bg-black/40 flex items-center justify-center">
              <span className="bg-white text-slate-700 font-bold px-4 py-2 rounded-full text-sm">
                Out of Stock
              </span>
            </div>
          )}

          {/* Quick actions */}
          <div className="absolute top-2 right-2 flex flex-col gap-2 opacity-0 group-hover:opacity-100 transition-all duration-200 translate-x-2 group-hover:translate-x-0">
            <button
              onClick={(e) => { e.preventDefault(); toast("Added to wishlist!"); }}
              className="w-8 h-8 rounded-full bg-white shadow-md flex items-center justify-center hover:bg-sky-50 transition-colors"
            >
              <Heart className="w-3.5 h-3.5 text-slate-600" />
            </button>
            <button
              onClick={(e) => { e.preventDefault(); e.stopPropagation(); router.push(`/products/${product.slug}`); }}
              className="w-8 h-8 rounded-full bg-white shadow-md flex items-center justify-center hover:bg-sky-50 transition-colors"
            >
              <Eye className="w-3.5 h-3.5 text-slate-600" />
            </button>
          </div>

          {/* Add to cart hover bar */}
          {product.stock > 0 && (
            <button
              onClick={handleAddToCart}
              className="absolute bottom-0 left-0 right-0 bg-gradient-to-r from-sky-600 to-sky-500 text-white py-2.5 text-sm font-bold flex items-center justify-center gap-2 translate-y-full group-hover:translate-y-0 transition-transform duration-300"
            >
              <ShoppingCart className="w-4 h-4" /> Add to Cart
            </button>
          )}
        </div>

        {/* Info */}
        <div className="p-3 sm:p-4">
          <p className="text-xs text-sky-600 font-medium mb-1">{product.brand.name}</p>
          <h3 className="text-sm font-semibold text-slate-800 line-clamp-2 group-hover:text-sky-700 transition-colors leading-snug mb-2">
            {product.name}
          </h3>

          {/* Rating */}
          {avgRating !== null && (
            <div className="flex items-center gap-1 mb-2">
              <div className="flex">
                {[1, 2, 3, 4, 5].map((star) => (
                  <Star
                    key={star}
                    className={cn("w-3 h-3", star <= Math.round(avgRating) ? "text-amber-400 fill-amber-400" : "text-slate-200 fill-slate-200")}
                  />
                ))}
              </div>
              <span className="text-xs text-slate-500">({product.reviews?.length})</span>
            </div>
          )}

          {/* Price */}
          <div className="flex items-end gap-2">
            <span className="text-lg font-black text-slate-900">{formatPrice(product.price)}</span>
            {product.comparePrice && (
              <span className="text-sm text-slate-400 line-through">{formatPrice(Number(product.comparePrice))}</span>
            )}
          </div>

          {/* Stock indicator */}
          {product.stock > 0 && product.stock <= 5 && (
            <p className="text-xs text-orange-500 font-medium mt-1">Only {product.stock} left!</p>
          )}
        </div>
      </div>
    </Link>
  );
}
