import RecipeCard from "../components/RecipeCard.tsx"
import { useParams } from "react-router-dom";
import { useState, useEffect } from "react";
import { getRecipeById } from "../services/frontendApi.js";
import { type Recipe } from "../types/Recipe"

function RecipePage() {
  const [recipe, setRecipe] = useState<Recipe>({
    details: {},
    ingredients: [],
    steps: {}
  });
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const { id } = useParams();

  useEffect(() => {
    const loadRecipe = async () => {
      try {
        const recipe = await getRecipeById(id);
        setRecipe(recipe);
        console.log(recipe)
      } catch (error) {
        console.log(error);
        setError("Failed to load recipes...");
      } finally {
        setLoading(false);
      }
    };
    loadRecipe();
  }, [id]);

  return (
    <div className="recipe">

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

      {loading ? (
        <div className="loading">Loading...</div>
      ) : (
        <div className="recipe-card">
          <RecipeCard recipe={recipe} key={recipe.details.id} />
        </div>
      )}
    </div>
  );
}

export default RecipePage;
