import { useState } from "react";
import { useTranslation } from "react-i18next";
import { apiClient } from "../../../api/client";
import { FavoriteIcon } from "../../../layouts/nav-icons";
import "../recipes.scss";

/**
 * Star toggle for a recipe's favorite status — the overlay button on
 * {@link RecipeDetailPanel}'s photo header. Optimistic: flips immediately,
 * calls the API in the background, and reverts if it fails (favoriting is
 * rare enough, and low-stakes enough, that a rollback-on-error is simpler
 * and just as correct as a pending state).
 *
 * `onToggled` lets the owning page (`RecipesPage`) keep the catalog table's
 * row (the fav-mark next to the name, and the `favoris` tab's membership)
 * in sync — this component only owns the button's own optimistic look.
 */
export function FavoriteStarButton({
  recipeId,
  isFavorite,
  onToggled,
}: {
  recipeId: number;
  isFavorite: boolean;
  onToggled: (isFavorite: boolean) => void;
}) {
  const { t } = useTranslation();
  const [isSaving, setIsSaving] = useState(false);

  async function handleClick() {
    const next = !isFavorite;
    onToggled(next);
    setIsSaving(true);
    try {
      if (next) {
        await apiClient.addFavoriteRecipe(recipeId);
      } else {
        await apiClient.removeFavoriteRecipe(recipeId);
      }
    } catch {
      onToggled(!next);
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <button
      type="button"
      className={`favorite-star-button${isFavorite ? " is-favorite" : ""}`}
      onClick={handleClick}
      disabled={isSaving}
      title={t(isFavorite ? "recipes.detail.unfavorite" : "recipes.detail.favorite")}
    >
      <FavoriteIcon aria-hidden="true" />
    </button>
  );
}
