package com.pixelized.biblib.ui.navigation

import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.NavOptionsBuilder
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.dialog
import androidx.navigation.compose.rememberNavController
import com.pixelized.biblib.ui.screen.authentication.AuthenticationScreen
import com.pixelized.biblib.ui.screen.home.HomeScreen
import com.pixelized.biblib.ui.screen.home.profile.ProfilePage

val LocalScreenNavHostController = compositionLocalOf<NavHostController> {
    error("LocalFullScreenNavHostController is not ready yet.")
}

@Composable
fun ScreenNavHost(
    modifier: Modifier = Modifier,
    navHostController: NavHostController = rememberNavController(),
    startDestination: Screen = Screen.Authentication
) {
    CompositionLocalProvider(
        LocalScreenNavHostController provides navHostController,
    ) {
        NavHost(
            modifier = modifier,
            navController = navHostController,
            startDestination = startDestination.route,
        ) {
            composable(Screen.Authentication.route) {
                AuthenticationScreen()
            }
            composable(Screen.Home.route) {
                HomeScreen()
            }
            dialog(Screen.Profile.route) {
                ProfilePage()
            }
        }
    }
}

fun NavHostController.navigateToAuthentication(
    option: NavOptionsBuilder.() -> Unit = rootOption(),
) {
    navigate(route = Screen.Authentication.route, builder = option)
}

fun NavHostController.navigateToHome(
    option: NavOptionsBuilder.() -> Unit = rootOption(),
) {
    navigate(route = Screen.Home.route, builder = option)
}

fun NavHostController.navigateToProfile(
    option: NavOptionsBuilder.() -> Unit = defaultOption(),
) {
    navigate(route = Screen.Profile.route, builder = option)
}

fun defaultOption(): NavOptionsBuilder.() -> Unit = { }

fun rootOption(): NavOptionsBuilder.() -> Unit = {
    launchSingleTop = true
    restoreState = true
    popUpTo(0) {
        saveState = true
        inclusive = true
    }
}