"use client";

import React, { useState, useOptimistic, useCallback } from "react";
import { Heart } from "lucide-react";
import toast from "react-hot-toast";
import { useTranslations } from "next-intl";
import useFavourites from "@/hooks/use-favourites";
import { Product } from "@/lib/types/product";

interface FavouriteButtonProps {
    product: Product;
    /** Icon size in px (default 20) */
    size?: number;
    /** Extra classes applied to the wrapper button */
    className?: string;
}

/**
 * Favourite / Wishlist toggle button with **optimistic UI**.
 * Heart fills instantly on click; if the API fails the state reverts
 * and an error toast is displayed.
 */
export default function FavouriteButton({
    product,
    size = 20,
    className = "",
}: FavouriteButtonProps) {
    const { isFavourite, toggleFavourite } = useFavourites();
    const t = useTranslations("favourites");
    const [isToggling, setIsToggling] = useState(false);

    const serverActive = isFavourite(product.id);

    // Optimistic state: toggle instantly in the UI
    const [optimisticActive, setOptimisticActive] = useOptimistic(
        serverActive,
        (_current: boolean, next: boolean) => next
    );

    const handleClick = useCallback(
        async (e: React.MouseEvent) => {
            e.stopPropagation();
            e.preventDefault();

            if (isToggling) return;

            // Toggle UI instantly
            const willBeFav = !optimisticActive;
            setOptimisticActive(willBeFav);

            try {
                setIsToggling(true);
                const nowFav = await toggleFavourite(product);

                if (nowFav) {
                    toast.success(t("addedToFavourites") || "تمت الإضافة إلى المفضلة");
                } else {
                    toast(t("removedFromFavourites") || "تمت الإزالة من المفضلة", {
                        icon: "💔",
                    });
                }
            } catch (error: any) {
                // Revert optimistic state on failure
                setOptimisticActive(serverActive);
                const message = typeof error === "string" ? error : error?.message;
                toast.error(message || "حدث خطأ");
            } finally {
                setIsToggling(false);
            }
        },
        [isToggling, optimisticActive, serverActive, setOptimisticActive, toggleFavourite, product, t]
    );

    return (
        <button
            type="button"
            onClick={handleClick}
            disabled={isToggling}
            aria-label={
                optimisticActive
                    ? t("removeFromFavourites") || "إزالة من المفضلة"
                    : t("addToFavourites") || "أضف إلى المفضلة"
            }
            className={`
        group relative flex items-center justify-center
        w-9 h-9 rounded-full bg-transparent backdrop-blur-sm
        transition-all duration-200 ease-out
        hover:scale-110 hover:shadow-md
        active:scale-95
        disabled:opacity-50
        ${className}
      `}
        >
            <Heart
                size={size}
                data-favourite-active={optimisticActive ? "true" : undefined}
                className="transition-all duration-300 ease-out"
                style={{
                    transform: optimisticActive ? "scale(1.1)" : "scale(1)",
                }}
                strokeWidth={optimisticActive ? 1.5 : 2}
            />

            {/* Pulse animation on toggle */}
            {optimisticActive && (
                <span className="absolute inset-0 rounded-full animate-ping bg-red-400/20 pointer-events-none" />
            )}
        </button>
    );
}
