"use client";

import { useState } from "react";
import { Heart } from "lucide-react";
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,
}: {
  recipeId: string;
  initialFavorited?: boolean;
}) {
  const [favorited, setFavorited] = useState(initialFavorited);
  const [loading, setLoading] = useState(false);

  async function toggle() {
    setLoading(true);
    try {
      const res = await fetch(`/api/v1/recipes/${recipeId}/favorite`, {
        method: favorited ? "DELETE" : "POST",
      });
      if (!res.ok) return;
      setFavorited(!favorited);
    } finally {
      setLoading(false);
    }
  }

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