"use client";

import React, { useState } from "react";
import { Product } from "@/types";
import { useCart } from "@/context/CartContext";
import {
  Heart,
  Eye,
  ShoppingCart,
  Star,
  Check,
  Zap,
} from "lucide-react";

interface ProductCardProps {
  product: Product;
}

export const ProductCard: React.FC<ProductCardProps> = ({ product }) => {
  const {
    addToCart,
    buyNow,
    toggleWishlist,
    isInWishlist,
    openProductModal,
  } = useCart();

  const [addedAnimation, setAddedAnimation] = useState(false);
  const inWishlist = isInWishlist(product.id);

  const numericPrice = typeof product.price === "number" ? product.price : parseFloat(product.price);
  const numericOriginal = product.originalPrice
    ? typeof product.originalPrice === "number"
      ? product.originalPrice
      : parseFloat(product.originalPrice)
    : null;

  const discountPercent =
    numericOriginal && numericOriginal > numericPrice
      ? Math.round(((numericOriginal - numericPrice) / numericOriginal) * 100)
      : null;

  const handleAddToCart = (e: React.MouseEvent) => {
    e.stopPropagation();
    addToCart(product, 1);
    setAddedAnimation(true);
    setTimeout(() => setAddedAnimation(false), 1200);
  };

  const handleBuyNow = (e: React.MouseEvent) => {
    e.stopPropagation();
    buyNow(product, 1);
  };

  return (
    <div
      onClick={() => openProductModal(product)}
      className="group bg-white rounded-2xl border border-slate-200 hover:border-blue-900/40 shadow-sm hover:shadow-xl transition-all duration-300 flex flex-col overflow-hidden relative cursor-pointer"
    >
      {/* Discount / Special Badges */}
      <div className="absolute top-3 left-3 z-10 flex flex-col gap-1">
        {discountPercent && (
          <span className="bg-rose-600 text-white font-extrabold text-[11px] px-2.5 py-0.5 rounded-md shadow-sm">
            Save {discountPercent}%
          </span>
        )}
        {product.isBestSeller && (
          <span className="bg-amber-500 text-slate-950 font-bold text-[10px] uppercase tracking-wider px-2 py-0.5 rounded-md shadow-sm">
            Best Seller
          </span>
        )}
        {product.isSchoolEssential && (
          <span className="bg-blue-900 text-white font-semibold text-[10px] px-2 py-0.5 rounded-md shadow-sm">
            School Essential
          </span>
        )}
      </div>

      {/* Wishlist Button */}
      <button
        onClick={(e) => {
          e.stopPropagation();
          toggleWishlist(product);
        }}
        className={`absolute top-3 right-3 z-10 w-8 h-8 rounded-full flex items-center justify-center transition-all ${
          inWishlist
            ? "bg-rose-50 text-rose-600 shadow-md"
            : "bg-white/80 hover:bg-white text-slate-400 hover:text-rose-600 shadow-sm"
        }`}
        title={inWishlist ? "Remove from wishlist" : "Add to wishlist"}
      >
        <Heart className={`w-4 h-4 ${inWishlist ? "fill-rose-600" : ""}`} />
      </button>

      {/* Image Wrapper */}
      <div className="relative pt-[80%] bg-slate-100 overflow-hidden">
        <img
          src={product.image}
          alt={product.name}
          className="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
        />

        {/* Quick View Hover Overlay */}
        <div className="absolute inset-0 bg-slate-950/20 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
          <button
            onClick={(e) => {
              e.stopPropagation();
              openProductModal(product);
            }}
            className="px-3.5 py-2 bg-white/95 text-slate-900 font-bold text-xs rounded-xl shadow-lg hover:bg-white flex items-center gap-1.5 transform translate-y-2 group-hover:translate-y-0 transition-all"
          >
            <Eye className="w-3.5 h-3.5 text-blue-900" /> Quick View
          </button>
        </div>
      </div>

      {/* Card Content */}
      <div className="p-4 flex-1 flex flex-col justify-between">
        <div>
          {/* Brand & Stock Header */}
          <div className="flex items-center justify-between gap-2 text-xs mb-1">
            <span className="font-bold text-amber-700 uppercase tracking-wider text-[11px]">
              {product.brandName}
            </span>
            <span className="text-[10px] font-semibold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200">
              In Stock
            </span>
          </div>

          {/* Product Name */}
          <h3 className="font-bold text-slate-900 text-sm line-clamp-2 leading-snug group-hover:text-blue-900 transition-colors">
            {product.name}
          </h3>

          {/* Rating */}
          <div className="flex items-center gap-1.5 mt-2">
            <div className="flex items-center text-amber-400">
              <Star className="w-3.5 h-3.5 fill-amber-400" />
            </div>
            <span className="text-xs font-bold text-slate-800">
              {Number(product.rating || 4.8).toFixed(1)}
            </span>
            <span className="text-slate-400 text-xs">
              ({product.reviewCount || 18})
            </span>
          </div>
        </div>

        {/* Price & Action Buttons */}
        <div className="mt-4 pt-3 border-t border-slate-100 space-y-3">
          <div className="flex items-baseline gap-2">
            <span className="text-lg font-black text-slate-950">
              R{numericPrice.toFixed(2)}
            </span>
            {numericOriginal && numericOriginal > numericPrice && (
              <span className="text-xs text-slate-400 line-through font-medium">
                R{numericOriginal.toFixed(2)}
              </span>
            )}
          </div>

          <div className="grid grid-cols-2 gap-2">
            <button
              onClick={handleAddToCart}
              className={`py-2 px-2.5 rounded-xl text-xs font-extrabold flex items-center justify-center gap-1.5 transition-all cursor-pointer ${
                addedAnimation
                  ? "bg-emerald-600 text-white"
                  : "bg-blue-950 hover:bg-slate-900 text-white shadow-sm"
              }`}
            >
              {addedAnimation ? (
                <>
                  <Check className="w-3.5 h-3.5" />
                  <span>Added</span>
                </>
              ) : (
                <>
                  <ShoppingCart className="w-3.5 h-3.5 text-amber-400" />
                  <span>Add Cart</span>
                </>
              )}
            </button>

            <button
              onClick={handleBuyNow}
              className="py-2 px-2.5 bg-amber-500 hover:bg-amber-600 text-slate-950 font-extrabold text-xs rounded-xl flex items-center justify-center gap-1 transition-all shadow-sm cursor-pointer"
            >
              <Zap className="w-3 h-3 fill-slate-950" />
              <span>Buy Now</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
