import CookbookRecipeTile from "../components/CookbookRecipeTile.tsx"
import { useState, useEffect } from "react";
import { getRecipes, deleteRecipe } from "../services/frontendApi.js";
import { type Recipe } from "../types/Recipe"

function Cookbook() {
  const [recipes, setRecipes] = useState([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [shouldFetchRecipes, setShouldFetchRecipes] = useState(true);

  useEffect(() => {
    const loadRecipes = async () => {
      try {
        const recipes = await getRecipes();
        setRecipes(recipes);
      } catch (error) {
        console.log(error);
        setError("Failed to load recipes...");
      } finally {
        setLoading(false);
      }
    };
    if (shouldFetchRecipes) {
      loadRecipes().then(() => setShouldFetchRecipes(false));
    }
  }, [shouldFetchRecipes]);

  const handleDelete = async (id: number | void) => {
    try {
      await deleteRecipe(id);
      setShouldFetchRecipes(true);
    } catch (error) {
      console.error("Error deleting recipe:", error);
    }
  };


  return (
    <div className="home">

      {error && <div className="error-message">{error}</div>}

      {loading ? (
        <div className="loading">Loading...</div>
      ) : (
        <div className="recipes-grid">
          {recipes.map((recipe: Recipe) => (
            <CookbookRecipeTile recipe={recipe} key={recipe.id} handleDelete={handleDelete} />
          ))}
        </div>
      )}
    </div>
  );
}

export default Cookbook;
