import { useAuth } from "@/_core/hooks/useAuth";
import { trpc } from "@/lib/trpc";
import { useLocation } from "wouter";

export default function FavoritoButton({
  episodioId,
  className = "",
}: {
  episodioId: number;
  className?: string;
}) {
  const { user } = useAuth();
  const [, navigate] = useLocation();
  const utils = trpc.useUtils();

  const favoritoQuery = trpc.podcast.isFavorito.useQuery(
    { episodioId },
    { enabled: !!user }
  );

  const toggleMutation = trpc.podcast.toggleFavorito.useMutation({
    onSuccess: result => {
      utils.podcast.isFavorito.setData({ episodioId }, result.favorited);
      utils.podcast.getFavoritos.invalidate();
    },
  });

  const isFavorito = favoritoQuery.data ?? false;

  return (
    <button
      type="button"
      onClick={e => {
        e.preventDefault();
        e.stopPropagation();
        if (!user) {
          navigate("/entrar");
          return;
        }
        toggleMutation.mutate({ episodioId });
      }}
      title={isFavorito ? "Remover dos favoritos" : "Adicionar aos favoritos"}
      className={`transition-colors ${isFavorito ? "text-sof-gold" : "text-sof-text-3 hover:text-sof-gold"} ${className}`}
    >
      {isFavorito ? "♥" : "♡"}
    </button>
  );
}
