"use client";

import { useState, useEffect } from "react";
import { Heart } from "lucide-react";
import { useRouter } from "next/navigation";

export default function ClientPortalFavoriteButton({
  productId,
  clientId,
  initialFavorites,
  primaryColor,
  onRequireLogin,
}: {
  productId: string;
  clientId?: string | null;
  initialFavorites?: string[] | null;
  primaryColor: string;
  onRequireLogin?: (productId: string) => void;
}) {
  const [isFavorite, setIsFavorite] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const router = useRouter();

  useEffect(() => {
    if (clientId && initialFavorites) setIsFavorite(initialFavorites.includes(productId));
    if (!clientId) setIsFavorite(false);
  }, [clientId, initialFavorites, productId]);

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

    if (isLoading) return;

    if (!clientId) {
      onRequireLogin?.(productId);
      return;
    }

    const nextState = !isFavorite;
    setIsFavorite(nextState);

    setIsLoading(true);
    try {
      const headers: Record<string, string> = { "Content-Type": "application/json" };

      const response = await fetch("/api/client-portal/favorites", {
        method: "POST",
        headers,
        /* A rota identifica o cliente pela sessao; o slug diz de qual loja e a
           sessao. O `clientId` que ia aqui nao vale mais como identidade. */
        body: JSON.stringify({
          productId,
          action: nextState ? "add" : "remove",
          slug: window.location.pathname.split("/").filter(Boolean)[0] || "",
        }),
      });
      if (!response.ok) {
        console.error("Failed to update favorite:", await response.text());
        // Revert on error
        setIsFavorite(!nextState);
      } else {
        // Se estivermos na aba de favoritos, força um reload pra já aparecer ou sumir o produto
        if (window.location.pathname.includes("/cliente")) {
           window.dispatchEvent(new Event("ks_favorites_updated"));
        } else {
           // Força invalidação do cache do Next.js para que ao navegar para o painel os dados venham frescos
           router.refresh();
        }
      }
    } catch (err) {
      setIsFavorite(!nextState);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <button
      type="button"
      onClick={toggleFavorite}
      className={`absolute top-2.5 right-2.5 z-20 h-8 w-8 rounded-full flex items-center justify-center transition-all ${
        isFavorite
          ? "bg-white text-rose-500 shadow-md"
          : "bg-white/70 backdrop-blur-sm text-gray-500 hover:bg-white hover:text-rose-500 shadow-sm border border-white/50"
      }`}
      aria-label={isFavorite ? "Remover dos favoritos" : "Adicionar aos favoritos"}
    >
      <Heart size={16} className={isFavorite ? "fill-current" : ""} />
    </button>
  );
}
