package dev.ulfrx.recipe.navigation

import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList

@Stable
class TabNavigator(
    initialTab: DockDestination = DockDestination.Default,
) {
    private val backStacks: Map<DockDestination, SnapshotStateList<Screen>> =
        DockDestination.entries.associateWith { dest -> mutableStateListOf(dest.startDestination) }

    var activeTab: DockDestination by mutableStateOf(initialTab)
        private set

    val activeBackStack: SnapshotStateList<Screen>
        get() = backStacks.getValue(activeTab)

    fun backStackFor(tab: DockDestination): SnapshotStateList<Screen> = backStacks.getValue(tab)

    fun selectTab(tab: DockDestination) {
        if (tab == activeTab) {
            popToRoot(tab)
        } else {
            activeTab = tab
        }
    }

    fun navigateTo(screen: Screen) {
        activeBackStack.add(screen)
    }

    fun goBack(tab: DockDestination = activeTab) {
        val stack = backStacks.getValue(tab)
        if (stack.size > 1) {
            stack.removeAt(stack.lastIndex)
        }
    }

    private fun popToRoot(tab: DockDestination) {
        val stack = backStacks.getValue(tab)
        while (stack.size > 1) {
            stack.removeAt(stack.lastIndex)
        }
    }
}
