import React, { memo, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useTranslations } from "next-intl";
import { formatCurrency } from "@/lib/utils";
import { Product } from "@/lib/types/product";
import AddToCartBtn from "./AddToCartBtn";
import FavouriteButton from "./favourite-button";
import StarRating from "./react-stars";

interface ProductCardProps {
  product: Product;
  onAddToCart?: (productId: number) => Promise<void>;
  showWishlist?: boolean;
}

const ProductCard = memo(function ProductCard({
  product,
  onAddToCart,
  showWishlist = true,
}: ProductCardProps) {
  const t = useTranslations("products");
  const pathname = usePathname();
  const locale = pathname?.split("/")[1] || "ar";

  const [imgError, setImgError] = useState(false);
  const [isAdding, setIsAdding] = useState(false);
  const [addSuccess, setAddSuccess] = useState(false);

  const formattedPrice = formatCurrency(product.price, locale);
  const formattedOldPrice =
    product.oldPrice && product.oldPrice > product.price
      ? formatCurrency(product.oldPrice, locale)
      : null;

  const handleAddToCart = async (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (!product.inStock || isAdding || !onAddToCart) return;

    try {
      setIsAdding(true);
      await onAddToCart(product.id);
      setAddSuccess(true);
      setTimeout(() => setAddSuccess(false), 1600);
    } finally {
      setIsAdding(false);
    }
  };

  return (
    <div className="relative w-full h-full flex flex-col bg-white rounded-2xl overflow-visible hover:shadow-lg transition-shadow font-[family-name:var(--font-cairo)]">
      {showWishlist && (
        <div className="absolute top-3 z-10" style={{ insetInlineStart: "12px" }}>
          <FavouriteButton product={product} size={22} />
        </div>
      )}

      <Link href={`/${locale}/product/${product.id}`}>
        <div className="relative w-full aspect-square bg-gray-50 overflow-hidden cursor-pointer rounded-t-2xl">
          {product.imageUrl && !imgError ? (
            <Image
              src={product.imageUrl}
              alt={product.name}
              fill
              sizes="(max-width: 768px) 100vw, (max-width: 1024px) 50vw, 25vw"
              className="object-contain bg-white hover:scale-105 transition-transform duration-300 p-2"
              onError={() => setImgError(true)}
            />
          ) : (
            <div className="w-full h-full bg-gray-100 flex items-center justify-center">
              <span className="text-3xl font-bold text-gray-300">{product.name?.charAt(0) || "?"}</span>
            </div>
          )}
        </div>
      </Link>

      <div className="px-3 pt-3 pb-2 flex flex-col flex-grow">
        <div className="flex items-center gap-2 mb-1">
          <Link href={`/${locale}/product/${product.id}`} className="min-w-0 flex-1">
            <p className="text-[14px] text-gray-800 line-clamp-1 leading-snug cursor-pointer hover:text-gray-900 transition-colors font-semibold">
              {product.brand || t("brand-fallback")}
              {product.isVerified && (
                <Image
                  src="/icons svg/Twitter_Verified_Badge.svg.png"
                  alt={t("verified")}
                  width={16}
                  height={16}
                  className="w-4 h-4 inline-block ms-1 align-middle flex-shrink-0"
                />
              )}
            </p>
          </Link>

          {product.category && (
            <span className="inline-block text-[11px] font-medium text-white bg-[#B5B5B5] rounded-md px-2.5 py-0.5 flex-shrink-0">
              {product.category}
            </span>
          )}
        </div>

        <p className="text-[12px] text-gray-500 line-clamp-1 leading-relaxed mb-1">
          {product.description}
        </p>

        <div className="flex items-end justify-between mb-2">
          <div className="flex items-baseline gap-2">
            <span className="text-[18px] font-bold text-gray-900">{formattedPrice}</span>
            {formattedOldPrice && (
              <span className="text-gray-400 line-through text-[14px]">{formattedOldPrice}</span>
            )}
          </div>

          <div className="flex flex-col items-end gap-1">
            <StarRating rating={product.rating || 5} inline className="inline-flex" size={16} />
            {Number(product.discount) > 0 && (
              <span className="bg-red-500 text-white flex items-center justify-center rounded-full px-1.5 py-0.5 text-[12px] font-bold min-w-[40px]">
                {product.discount}%
              </span>
            )}
          </div>
        </div>

        <div className="flex-grow" />

        <AddToCartBtn
          onClick={handleAddToCart}
          disabled={isAdding || !product.inStock}
          label={isAdding ? t("adding") : undefined}
          showSuccess={addSuccess}
        />
      </div>
    </div>
  );
});

export default ProductCard;
