"use client";

import { useState } from "react";
import { Heart } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
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 (
    <Button variant="ghost" size="sm" onClick={toggle} disabled={loading} className="gap-1.5">
      <Heart className={cn("h-4 w-4", favorited && "fill-red-500 text-red-500")} />
      {favorited ? "Saved" : "Save"}
    </Button>
  );
}
