package dev.ulfrx.recipe.ui.screens.recipedetail

import androidx.lifecycle.ViewModel
import dev.ulfrx.recipe.ui.components.recipe.options
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

class RecipeDetailViewModel(recipeId: String) : ViewModel() {
    private val _state = MutableStateFlow(sampleRecipe(recipeId)?.let(RecipeDetailState::Ready) ?: RecipeDetailState.NotFound)
    val state: StateFlow<RecipeDetailState> = _state.asStateFlow()

    fun setServings(value: Int) =
        _state.update { current ->
            if (current is RecipeDetailState.Ready) {
                current.copy(servings = value.coerceIn(MIN_RECIPE_SERVINGS, MAX_RECIPE_SERVINGS))
            } else {
                current
            }
        }

    fun selectSubstitution(
        slotId: String,
        optionId: String,
    ) = _state.update { current ->
        if (current !is RecipeDetailState.Ready) return@update current
        val slot = current.recipe.ingredients.firstOrNull { it.id == slotId } ?: return@update current
        if (slot.options.none { it.id == optionId }) return@update current

        val substitutions =
            if (optionId == slot.default.id) {
                current.substitutions - slotId
            } else {
                current.substitutions + (slotId to optionId)
            }
        current.copy(substitutions = substitutions)
    }
}
