import { MouseEvent } from "react";
import { Link, useNavigate } from "react-router-dom";
import { ShoppingCart, ShoppingBag, Scale } from "lucide-react";
import { formatPrice, PRIMARY_CURRENCY } from "@/lib/currency";
import { Price } from "@/components/ui/Price";
import { useCart } from "@/context/CartContext";
import { useCompare, COMPARE_LIMIT } from "@/context/CompareContext";

export interface ProductCardData {
  id: number;
  name: string;
  slug: string;
  description?: string | null;
  product_type: string;
  price: number;
  compare_at_price?: number | null;
  currency?: string | null;
  image_url?: string | null;
  stock?: number | null;
  featured?: boolean | null;
  category?: string | null;
}

interface ProductCardProps {
  product: ProductCardData;
}

/**
 * Minimalist marketplace-style product card inspired by the concept reference.
 *
 * Visual anatomy (top → bottom):
 *   1. Small uppercase category tag (light-gray).
 *   2. Bold blue product title (2-line clamp).
 *   3. Large centered product image on a white background.
 *   4. Price row: sale price (red) or regular price (black/slate),
 *      with an optional struck-through compare-at price directly below.
 *   5. Circular "Add to cart" action button on the bottom-right.
 *
 * The whole card is a link to the product detail page. The add-to-cart button
 * stops propagation so clicking it does not navigate away.
 */
export default function ProductCard({ product }: ProductCardProps) {
  // Display Saudi Riyal as the primary currency across the storefront.
  void product.currency; // acknowledge unused legacy field
  const currency = PRIMARY_CURRENCY;

  const navigate = useNavigate();
  const { addToCart } = useCart();
  const { has: isInCompare, toggle: toggleCompare, items: compareItems, openDrawer } = useCompare();
  const inCompare = isInCompare(product.id);
  const compareDisabled = !inCompare && compareItems.length >= COMPARE_LIMIT;

  const handleToggleCompare = (e: MouseEvent<HTMLButtonElement>) => {
    // Prevent the parent <Link> from navigating when the compare button is
    // pressed. The shopper stays on the listing so they can continue
    // selecting products.
    e.preventDefault();
    e.stopPropagation();
    if (compareDisabled) {
      // Already at the limit and this item is not selected — open the drawer
      // so the user can remove something before adding more.
      openDrawer();
      return;
    }
    toggleCompare(product);
  };

  const hasDiscount =
    product.compare_at_price &&
    product.compare_at_price > 0 &&
    product.compare_at_price > product.price;

  // Derive a short, readable category label. We prefer an explicit category
  // field; otherwise we fall back to a capitalized product_type. This keeps
  // the top-of-card metadata useful regardless of how the backend shape evolves.
  const categoryLabel = (() => {
    if (product.category && product.category.trim().length > 0) {
      return product.category.toUpperCase();
    }
    if (product.product_type === "digital") return "DIGITAL";
    if (product.product_type === "hosting") return "HOSTING";
    return "PHYSICAL";
  })();

  const handleAddToCart = (e: MouseEvent<HTMLButtonElement>) => {
    // Prevent the surrounding <Link> from navigating when the quick-add
    // button is pressed. Users stay on the listing page after adding.
    e.preventDefault();
    e.stopPropagation();
    if (product.stock !== null && product.stock !== undefined && product.stock <= 0) {
      // Out-of-stock items redirect to the product page instead of adding.
      navigate(`/shop/${product.slug}`);
      return;
    }
    addToCart({
      product_id: product.id,
      name: product.name,
      slug: product.slug,
      product_type: product.product_type,
      variant_label: "default",
      unit_price: product.price,
      currency,
      quantity: 1,
      image_url: product.image_url || "",
      stock:
        product.stock === null || product.stock === undefined ? -1 : product.stock,
    });
  };

  const outOfStock =
    product.stock !== null && product.stock !== undefined && product.stock <= 0;

  return (
    <Link
      to={`/shop/${product.slug}`}
      className="group bg-white rounded-xl border border-slate-200 overflow-hidden hover:shadow-lg hover:-translate-y-0.5 transition flex flex-col"
    >
      {/* Top metadata: small uppercase category tag */}
      <div className="px-4 pt-4">
        <div className="text-[10px] font-semibold tracking-[0.15em] text-slate-400 uppercase truncate">
          {categoryLabel}
        </div>
        <h3 className="mt-1 font-bold text-[#1b3a8c] text-sm md:text-[15px] leading-snug line-clamp-2 min-h-[2.5rem] group-hover:text-slate-900 transition">
          {product.name}
        </h3>
      </div>

      {/* Product image: large, centered, white background */}
      <div className="relative mx-4 mt-3 aspect-square bg-white overflow-hidden flex items-center justify-center">
        {product.image_url ? (
          <img
            src={product.image_url}
            alt={product.name}
            className="max-w-full max-h-full object-contain group-hover:scale-105 transition-transform duration-500"
            loading="lazy"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center text-slate-200">
            <ShoppingBag className="w-16 h-16" />
          </div>
        )}
        {outOfStock && (
          <span className="absolute top-2 left-2 bg-slate-900/85 text-white text-[10px] font-bold px-2 py-0.5 rounded-full">
            Out of stock
          </span>
        )}
      </div>

      {/* Price row + circular add-to-cart action */}
      <div className="px-4 pb-4 pt-3 mt-auto flex items-end justify-between gap-3">
        <div className="min-w-0">
          {hasDiscount ? (
            <>
              <div className="text-lg md:text-xl font-extrabold text-rose-600 leading-none">
                <Price amount={product.price} />
              </div>
              <div className="mt-1 text-xs text-slate-400 line-through">
                <Price amount={product.compare_at_price!} />
              </div>
            </>
          ) : (
            <>
              <div className="text-lg md:text-xl font-extrabold text-slate-900 leading-none">
                <Price amount={product.price} />
              </div>
              <div className="mt-1 text-[10px] uppercase tracking-wider text-slate-400">
                {currency}
              </div>
            </>
          )}
        </div>

        <div className="shrink-0 flex items-center gap-2">
          <button
            type="button"
            onClick={handleToggleCompare}
            aria-label={
              inCompare
                ? `Remove ${product.name} from compare`
                : `Add ${product.name} to compare`
            }
            aria-pressed={inCompare}
            title={
              compareDisabled
                ? `You can compare up to ${COMPARE_LIMIT} products`
                : inCompare
                  ? "Remove from compare"
                  : "Add to compare"
            }
            className={
              "w-10 h-10 rounded-full flex items-center justify-center transition shadow-sm " +
              (inCompare
                ? "bg-[#0b6e3e] text-white hover:bg-[#0a8048]"
                : "bg-slate-100 text-slate-700 hover:bg-slate-200")
            }
          >
            <Scale className="w-4 h-4" />
          </button>
          <button
            type="button"
            onClick={handleAddToCart}
            aria-label={outOfStock ? "View product" : `Add ${product.name} to cart`}
            className="w-10 h-10 rounded-full bg-slate-100 hover:bg-[#FFD500] text-slate-700 hover:text-slate-900 flex items-center justify-center transition shadow-sm"
          >
            <ShoppingCart className="w-4 h-4" />
          </button>
        </div>
      </div>
    </Link>
  );
}