package dev.adriankuta.flights.ui

import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarDefaults
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import dev.adriankuta.flights.navigation.FlightsNavGraph
import dev.adriankuta.flights.navigation.TopLevelDestination
import dev.adriankuta.flights.navigation.navigateToTopLevelDestination
import dev.adriankuta.flights.ui.designsystem.theme.Elevation

@Composable
fun FlightsApp(
    modifier: Modifier = Modifier,
) {
    val navController = rememberNavController()

    Surface(
        tonalElevation = Elevation.Surface,
        modifier = modifier,
    ) {
        Scaffold(
            snackbarHost = { InAppUpdates() },
            bottomBar = {
                FlightsBottomBar(
                    navController = navController,
                )
            },
        ) { paddingValues ->
            FlightsNavGraph(
                navController = navController,
                modifier = Modifier.padding(paddingValues),
            )
        }
    }
}

@Composable
internal fun FlightsBottomBar(
    navController: NavHostController = rememberNavController(),
) {
    var selectedDestination by rememberSaveable { mutableIntStateOf(0) }

    NavigationBar(windowInsets = NavigationBarDefaults.windowInsets) {
        TopLevelDestination.entries.forEachIndexed { index, destination ->
            NavigationBarItem(
                selected = selectedDestination == index,
                onClick = {
                    selectedDestination = index
                    navController.navigateToTopLevelDestination(destination)
                },
                icon = {
                    Icon(
                        destination.icon,
                        contentDescription = null,
                    )
                },
                label = { Text(stringResource(destination.titleTextId)) },
            )
        }
    }
}
