import React, { useState, useEffect } from "react";
import { Heart } from "lucide-react";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { useNavigate } from "react-router-dom";

export default function ProductCard({ product }) {
    const API = import.meta.env.VITE_API_URL;

    const [hover, setHover] = useState(false);
    const [liked, setLiked] = useState(false);
    const [animateHeart, setAnimateHeart] = useState(false);


    // Build dynamic image list (1–15 images)
    const images = (product?.media || [])
        .map((m) => (m?.url ? `${API}${m.url}` : null))
        .filter(Boolean);

    if (images.length === 0) images.push("/no-image.png");

    const [index, setIndex] = useState(0);
    const navigate = useNavigate()

    useEffect(() => {
        let interval;
        if (hover && images.length > 1) {
            interval = setInterval(() => {
                setIndex((prev) => (prev + 1) % images.length);
            }, 1500);
        } else {
            setIndex(0);
        }
        return () => clearInterval(interval);
    }, [hover, images.length]);

    /* DISCOUNT */
    const discount =
        product.strikethroughPrice && product.price
            ? Math.round(
                ((product.strikethroughPrice - product.price) /
                    product.strikethroughPrice) * 100
            )
            : 0;

    /* RIBBON COLORS */
    const ribbonStyles = {
        Sale: "bg-red-600 text-white",
        New: "bg-green-600 text-white",
        Trending: "bg-orange-500 text-white",
        "Limited Edition": "bg-purple-600 text-white",
    };

    const ribbonClass =
        ribbonStyles[product.ribbon] || "bg-black/80 text-white";

    /* Backend values */
    const rating = product.rating || 4.5;
    const reviewsCount = product.reviewsCount || 24;
    const tags = product.tags || [];
    const colors = product.colors || [];
    const deliveryEstimate = product.deliveryEstimate || "2–4 days";

    const shortDescription =
        product.shortDescription ||
        (product.description
            ? product.description.replace(/<[^>]+>/g, "").slice(0, 90) + "…"
            : "");

    /* -------------------------------------------
        INVENTORY LOGIC
    -------------------------------------------- */

    const isTracking = product.trackInventory === true;
    const qty = Number(product.stockQuantity) || 0;

    const isLowStock = isTracking && qty > 0 && qty <= 10;
    const isOutOfStock = isTracking && qty <= 0;

    return (
        <div
        onClick={() => navigate(`/product/${product._id}`)}
            className="
                relative bg-white rounded-2xl p-3 shadow-sm hover:shadow-xl 
                transition-all duration-500 overflow-hidden 
                w-full max-w-[300px] 
                min-h-[520px]
                flex flex-col
                cursor-pointer group
            "
            onMouseEnter={() => setHover(true)}
            onMouseLeave={() => setHover(false)}
        >
            {/* RIBBON */}
            {product.ribbon && (
                <span
                    className={`absolute z-20 top-3 left-3 text-xs px-3 py-1 
                    rounded-full font-medium shadow-md ${ribbonClass}`}
                >
                    {product.ribbon}
                </span>
            )}

            {/* Wishlist Button */}
            <button
                onClick={(e) => {
                    e.stopPropagation();

                    const newState = !liked;
                    setLiked(newState);

                    // Trigger animation
                    setAnimateHeart(true);
                    setTimeout(() => setAnimateHeart(false), 400);

                    //  Toast OUTSIDE state updater -> NO DOUBLE CALL
                    if (newState) toast.success("Added to wishlist");
                    else toast.error("Removed from wishlist");
                }}
                className="absolute z-20 top-2 right-3 p-2 bg-white rounded-full shadow 
        hover:scale-110 transition-all border border-gray-200"
            >
                <Heart
                    size={18}
                    className={`
            ${liked ? "text-red-500" : "text-gray-700"}
            ${animateHeart ? "scale-150 opacity-90" : "scale-100"}
            transition-all duration-300 ease-out
        `}
                    fill={liked ? "red" : "none"}
                />
            </button>


            {/* IMAGES */}
            <div className="relative h-[230px] bg-gray-100 rounded-xl overflow-hidden">
                {images.map((img, i) => (
                    <img
                        key={i}
                        src={img}
                        loading="lazy"
                        className={`
                            w-full h-full object-contain absolute inset-0
                            transition-all duration-700
                            ${i === index ? "opacity-100 scale-105" : "opacity-0 scale-90"}
                        `}
                    />
                ))}

                {/* OUT OF STOCK BADGE */}
                {isOutOfStock && (
                    <div className="absolute inset-0 bg-black/40 flex items-center justify-center">
                        <span className="bg-red-600 text-white text-xs px-3 py-1 rounded-lg">
                            OUT OF STOCK
                        </span>
                    </div>
                )}
            </div>

            {/* CONTENT BELOW IMAGE */}
            <div className="flex flex-col flex-grow mt-3">

                {/* ⭐ RATING */}
                <div className="flex items-center gap-1">
                    <span className="text-yellow-500 text-sm">⭐</span>
                    <p className="text-sm font-medium">{rating}</p>
                    <p className="text-xs text-gray-500">({reviewsCount} reviews)</p>
                </div>

                {/* LOW STOCK */}
                {isLowStock && (
                    <p className="text-xs text-red-600 font-semibold mt-1">
                        ⚠ Only {qty} left!
                    </p>
                )}

                {/* TAGS */}
                {tags.length > 0 && (
                    <div className="flex flex-wrap gap-1 mt-2">
                        {tags.map((tag, i) => (
                            <span
                                key={i}
                                className="text-[10px] bg-orange-100 text-orange-700 px-2 py-1 rounded-md"
                            >
                                {tag}
                            </span>
                        ))}
                    </div>
                )}

                {/* COLORS */}
                {colors.length > 0 && (
                    <div className="flex gap-2 mt-2">
                        {colors.map((c, i) => (
                            <div
                                key={i}
                                className="w-4 h-4 rounded-full border shadow-sm"
                                style={{ background: c }}
                            />
                        ))}
                    </div>
                )}

                {/* DELIVERY */}
                <p className="text-xs text-gray-500 mt-2">
                    Delivery:{" "}
                    <span className="text-green-600 font-medium">
                        {deliveryEstimate}
                    </span>
                </p>

                {/* DESCRIPTION */}
                {shortDescription && (
                    <p className="text-xs text-gray-600 mt-2 line-clamp-2">
                        {shortDescription}
                    </p>
                )}

                {/* -------- DETAILS SECTION -------- */}
                <div className="mt-auto pt-3">

                    <p className="text-xs text-gray-500 font-medium">{product.brand}</p>

                    <h3 className="text-base font-semibold text-gray-900 line-clamp-2 mt-1">
                        {product.name}
                    </h3>

                    {/* PRICE */}
                    <div className="mt-2">
                        <div className="flex items-center gap-2">
                            <p className="text-lg font-semibold text-gray-900">
                                ₹{product.price}
                            </p>

                            {product.strikethroughPrice && (
                                <>
                                    <p className="text-xs line-through text-gray-400">
                                        ₹{product.strikethroughPrice}
                                    </p>
                                    {discount > 0 && (
                                        <span className="text-xs font-medium text-green-600">
                                            {discount}% off
                                        </span>
                                    )}
                                </>
                            )}
                        </div>

                        {discount > 0 && (
                            <p className="text-xs text-orange-600 font-medium">
                                Save ₹{product.strikethroughPrice - product.price}
                            </p>
                        )}
                    </div>

                    {/* BUTTONS */}
                    {isOutOfStock ? (
                        <Button className="w-full bg-gray-300 text-black mt-4 hover:bg-gray-400">
                            Notify Me When Back In Stock
                        </Button>
                    ) : (
                        <div className="mt-4 flex gap-2">
                            <Button className="w-1/2 bg-black text-white hover:bg-gray-900">
                                Add
                            </Button>
                            <Button className="w-1/2 bg-gray-200 text-black hover:bg-gray-300">
                                Buy
                            </Button>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
