package de.krisenvorrat.app.ui

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.SwapHoriz
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBarDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavDestination.Companion.hasRoute
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import de.krisenvorrat.app.ui.inventory.InventoryPickerSheet
import de.krisenvorrat.app.ui.inventory.InventoryPickerViewModel
import de.krisenvorrat.app.ui.navigation.KrisenvorratNavGraph
import de.krisenvorrat.app.ui.navigation.TopLevelDestination
import de.krisenvorrat.app.ui.update.UpdateBanner
import de.krisenvorrat.app.ui.update.UpdateViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun MainScreen() {
    val navController = rememberNavController()
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentDestination = navBackStackEntry?.destination

    val showBottomBar = TopLevelDestination.entries.any { topLevel ->
        currentDestination?.hasRoute(topLevel.route::class) == true
    }

    val inventoryPickerViewModel: InventoryPickerViewModel = hiltViewModel()
    val inventoryState by inventoryPickerViewModel.uiState.collectAsStateWithLifecycle()
    var isInventoryPickerVisible by remember { mutableStateOf(false) }

    val showTopBar = showBottomBar && inventoryState.activeInventoryName.isNotBlank()

    val updateViewModel: UpdateViewModel = hiltViewModel()
    val updateState by updateViewModel.uiState.collectAsStateWithLifecycle()

    Scaffold(
        topBar = {
            if (showTopBar) {
                TopAppBar(
                    title = {
                        Text(text = inventoryState.activeInventoryName)
                    },
                    actions = {
                        IconButton(onClick = { isInventoryPickerVisible = true }) {
                            Icon(
                                imageVector = Icons.Default.SwapHoriz,
                                contentDescription = "Inventar wechseln"
                            )
                        }
                    }
                )
            }
        },
        bottomBar = {
            if (showBottomBar) {
                Surface(
                    color = NavigationBarDefaults.containerColor,
                    tonalElevation = NavigationBarDefaults.Elevation
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .windowInsetsPadding(NavigationBarDefaults.windowInsets)
                            .padding(vertical = 4.dp),
                        horizontalArrangement = Arrangement.SpaceEvenly,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        TopLevelDestination.entries.forEach { destination ->
                            val isSelected = currentDestination?.hasRoute(destination.route::class) == true

                            IconButton(
                                onClick = {
                                    navController.navigate(destination.route) {
                                        popUpTo(navController.graph.findStartDestination().id) {
                                            saveState = true
                                        }
                                        launchSingleTop = true
                                        restoreState = true
                                    }
                                }
                            ) {
                                Icon(
                                    imageVector = if (isSelected) {
                                        destination.selectedIcon
                                    } else {
                                        destination.unselectedIcon
                                    },
                                    contentDescription = destination.label,
                                    tint = if (isSelected) {
                                        MaterialTheme.colorScheme.primary
                                    } else {
                                        MaterialTheme.colorScheme.onSurfaceVariant
                                    }
                                )
                            }
                        }
                    }
                }
            }
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .padding(innerPadding)
                .consumeWindowInsets(innerPadding)
        ) {
            UpdateBanner(
                status = updateState.status,
                onDownloadClick = updateViewModel::startDownload,
                onDismiss = updateViewModel::dismiss
            )
            KrisenvorratNavGraph(
                navController = navController,
                modifier = Modifier.weight(1f)
            )
        }
    }

    if (isInventoryPickerVisible) {
        InventoryPickerSheet(
            onDismiss = { isInventoryPickerVisible = false },
            viewModel = inventoryPickerViewModel
        )
    }
}
