package cl.homelogic.platform.navigation

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.navigation.NavUri
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import com.moriatsushi.insetsx.statusBars
import kotlinx.coroutines.flow.MutableSharedFlow

@Composable
fun NavigationSystem(
    navigationManager: NavigationManager,
    deeplinkStream: MutableSharedFlow<String>? = null,
    startDestination: NavigationDestination,
    navigationModules: List<NavigationModule>,
) {
    val navController = rememberNavController()

    LaunchedEffect(navController) {
        deeplinkStream?.collect {
            navController.navigate(NavUri(it))
        }
    }

    LaunchedEffect(navController) {
        navigationManager.navigationEvents.collect { command ->
            when (command) {
                is NavigationCommand.Route -> navController.navigate(command.destination)
                is NavigationCommand.DeepLink -> navController.navigate(command.uri)
                is NavigationCommand.PopBack -> navController.popBackStack()
                is NavigationCommand.PopUpTo -> navController.popBackStack(
                    command.destination,
                    command.inclusive,
                )
            }
        }
    }

    Box(
        modifier = Modifier
            .background(MaterialTheme.colorScheme.background)
            .fillMaxSize()
            .padding(
                top = WindowInsets.statusBars.asPaddingValues().calculateTopPadding(),
            ),
    ) {
        NavHost(
            navController = navController,
            startDestination = startDestination,
        ) {
            navigationModules.forEach { module ->
                module.navigationGraph(this, navController)
            }
        }
    }
}
