"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Heart } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";

export function FavoriteButton({
  recipeId,
  initialFavorited = false,
  onToggle,
  iconClassName,
}: {
  recipeId: string;
  initialFavorited?: boolean;
  /** Called after a successful toggle, e.g. to remove the recipe from a "Favorites" list view. */
  onToggle?: (favorited: boolean) => void;
  /** Extra classes for the heart icon when unfavorited — e.g. forcing a light color when the button overlays a photo. */
  iconClassName?: string;
}) {
  const tCommon = useTranslations("common");
  const tSocial = useTranslations("social");
  const [favorited, setFavorited] = useState(initialFavorited);
  const [loading, setLoading] = useState(false);

  async function toggle() {
    const next = !favorited;
    setFavorited(next);
    setLoading(true);
    try {
      const res = await fetch(`/api/v1/recipes/${recipeId}/favorite`, {
        method: next ? "POST" : "DELETE",
      });
      if (!res.ok) throw new Error();
      onToggle?.(next);
    } catch {
      setFavorited(!next);
      toast.error(tCommon("updateFailed"));
    } finally {
      setLoading(false);
    }
  }

  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger render={
          <Button
            variant="ghost"
            size="icon"
            onClick={toggle}
            disabled={loading}
            aria-label={favorited ? tSocial("favoriteRemove") : tSocial("favoriteAdd")}
          >
            <Heart className={cn("h-4 w-4", favorited ? "fill-red-500 text-red-500" : iconClassName)} />
          </Button>
        } />
        <TooltipContent>{favorited ? tSocial("favoriteRemove") : tSocial("favoriteAdd")}</TooltipContent>
      </Tooltip>
    </TooltipProvider>
  );
}
