import {useNavigate, useParams} from "react-router-dom"
import {useEffect, useState} from "react"
import type {RecipeModel} from "../../models/RecipeModel"
import {RecipeEditor} from "./RecipeEditor"
import {createOrUpdateRecipe, fetchRecipe} from "../../api/points/RecipePoint"
import {getRecipeDetailUrl, getRecipeListUrl} from "../../routes"
import {mapRecipeDtoToModel, mapRecipeModelToDto} from "../../mappers/RecipeMapper"
import type {RecipeDto} from "../../api/dtos/RecipeDto"

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

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

        loadRecipe()
    }, [id])

    const handleSave = async (updated: RecipeModel) => {
        try {
            const dto = mapRecipeModelToDto(updated);
            await createOrUpdateRecipe(dto);
            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}/>
}