import { useParams, useNavigate } from "react-router-dom"
import { useEffect, useState } from "react"
import type { Recipe } from "../../types/recipe"
import  RecipeEditor  from "./RecipeEditor"
import { fetchRecipe, createRecipe, updateRecipe } from "../../api/points/RecipePoint"
import { getRecipeDetailUrl, getRecipeListUrl } from "../../routes"

export default function RecipeEditPage() {
    // Extract recipe ID from route params
  const { id } = useParams<{ id: string }>()
  const [recipe, setRecipe] = useState<Recipe | null>(null)
  const navigate = useNavigate()

  useEffect(() => {
    const loadRecipe = async () => {
      if (id) {
        try {
          // Fetch recipe data when editing an existing one
          const data = await fetchRecipe(id)
          setRecipe(data)
        } catch (err) {
          console.error(err)
        }
      } else {
        // New recipe case
        setRecipe({
          id: "",
          title: "",
          ingredientGroupList: [
          ],
          instructions: "",
          servings: {
            amount: 1,
            unit: ""
          }
        })
      }
    }

    loadRecipe()
  }, [id])

  const handleSave = async (updated: Recipe) => {
    try {
      if (updated.id) {
        await updateRecipe(updated)
      } else {
        await createRecipe(updated)
      }
      navigateBack();
    } catch (err) {
      console.error(err)
    }
  }

 

 const handleCancel = () => {
    console.log("Cancelling edit mode for", recipe ? recipe.id : "no recipe at all")
    navigateBack();
 }

 const navigateBack = () => {
    if(recipe && recipe.id){
      console.log("navigating to recipe with id", recipe.id)
      navigate(getRecipeDetailUrl(recipe.id)) // go back to detail view
    } else {
      console.log("navigating back to list as no recipe was selected")
      navigate(getRecipeListUrl()) // no recipe -> go back to list
    }
 }
 // error handling -> if there is no recipe, we cannot open edit view
  if (!recipe) {
    return <div>Loading...</div>
  }
  
 return <RecipeEditor recipe={recipe} onSave={handleSave} onCancel={handleCancel}/>
}