package com.example.myapplication.ui.navigation

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
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.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.myapplication.ui.list.CartList
import com.example.myapplication.database.AppViewModelProvider
import com.example.myapplication.database.entities.composeui.edit.BikeEdit
import com.example.myapplication.ui.list.BikeList
import com.example.myapplication.ui.view.BikeView
import com.example.myapplication.database.room.viewmodel.user.CurrentUserViewModel
import com.example.myapplication.ui.list.LoginScreen
import com.example.myapplication.ui.list.RentList
import com.example.myapplication.ui.view.RentView
import com.example.myapplication.ui.list.ReportList
import com.example.myapplication.ui.list.UserList
import com.example.myapplication.setting.DataStoreManager
import com.example.myapplication.ui.edit.ItemEdit

@Composable
fun Topbar(
    navController: NavHostController,
    currentScreen: Screen?
) {
    var searchQuery by remember { mutableStateOf("") }
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .background(color = MaterialTheme.colorScheme.primary)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(10.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            if (
                navController.previousBackStackEntry != null
                && (currentScreen == null || !currentScreen.showInBottomBar)
            ) {
                Icon(
                    imageVector = Icons.Filled.ArrowBack,
                    contentDescription = null,
                    modifier = Modifier
                        .size(30.dp)
                        .clickable { navController.navigateUp() },
                    tint = MaterialTheme.colorScheme.secondary
                )
            } else
                Icon(
                    imageVector = Icons.Default.Person,
                    contentDescription = null,
                    modifier = Modifier
                        .size(30.dp)
                        .clickable { navController.navigate(Screen.UserProfile.route) },
                    tint = MaterialTheme.colorScheme.secondary
                )

            Spacer(modifier = Modifier.width(16.dp))

            BasicTextField(
                value = searchQuery,
                onValueChange = { newValue -> searchQuery = newValue },
                modifier = Modifier
                    .weight(1f)
                    .height(36.dp)
                    .background(
                        color = MaterialTheme.colorScheme.onPrimary,
                        RoundedCornerShape(18.dp)
                    )
                    .padding(start = 13.dp, top = 8.dp),
                keyboardOptions = KeyboardOptions.Default.copy(
                    imeAction = androidx.compose.ui.text.input.ImeAction.Search
                ),
                keyboardActions = KeyboardActions(
                    onSearch = { }
                )
            )

            Spacer(modifier = Modifier.width(16.dp))

            Icon(
                imageVector = Icons.Default.Search,
                contentDescription = null,
                modifier = Modifier
                    .size(30.dp)
                    .clickable { },
                tint = MaterialTheme.colorScheme.secondary
            )
        }
    }
}

@Composable
fun Navbar(
    navController: NavHostController,
    currentDestination: NavDestination?,
    modifier: Modifier = Modifier
) {
    NavigationBar(modifier = modifier, containerColor = MaterialTheme.colorScheme.primary) {
        Screen.bottomBarItems.forEach { screen ->
            NavigationBarItem(
                icon = {
                    Icon(
                        screen.icon,
                        contentDescription = null,
                        tint = if (currentDestination?.hierarchy?.any { it.route == screen.route } == true)
                            MaterialTheme.colorScheme.primary
                        else
                            MaterialTheme.colorScheme.secondary
                    )
                },
                label = {    Text(
                        stringResource(screen.resourceId),
                        color = MaterialTheme.colorScheme.secondary
                    ) },
                selected = currentDestination?.hierarchy?.any { it.route == screen.route } == true,
                onClick = {
                    navController.navigate(screen.route) {
                        popUpTo(navController.graph.findStartDestination().id) {
                            saveState = true
                        }
                        launchSingleTop = true
                        restoreState = true
                    }
                }
            )
        }
    }
}

@Composable
fun Navhost(
    navController: NavHostController,
    innerPadding: PaddingValues,
    isDarkTheme: MutableState<Boolean>,
    dataStore: DataStoreManager,
    modifier: Modifier = Modifier,
    currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)
) {
    NavHost(
        navController,
        startDestination = Screen.BikeList.route,
        modifier.padding(innerPadding)
    ) {
        composable(Screen.BikeList.route) { BikeList(navController, currentUserViewModel = currentUserViewModel) }
        composable(Screen.RentList.route) { RentList(navController, currentUserViewModel = currentUserViewModel) }
        composable(Screen.Cart.route) { CartList(currentUserViewModel = currentUserViewModel) }
        composable(Screen.UserProfile.route) { UserList(navController,isDarkTheme, dataStore, currentUserViewModel = currentUserViewModel) }
        composable(Screen.Report.route) { ReportList(navController = navController) }
        composable(Screen.LoginScreen.route) { LoginScreen(navController) }
        composable(
            Screen.BikeEdit.route,
            arguments = listOf(navArgument("id") { type = NavType.IntType })
        ) {
            BikeEdit(navController)
        }
        composable(
            Screen.ItemEdit.route,
            arguments = listOf(navArgument("id") { type = NavType.IntType },
                navArgument("bikeId") { type = NavType.IntType })
        ) {
            ItemEdit(navController,currentUserViewModel = currentUserViewModel)
        }
        composable(
            Screen.BikeView.route,
            arguments = listOf(navArgument("id") { type = NavType.IntType })
        ) { backStackEntry ->
            backStackEntry.arguments?.let { BikeView(navController, currentUserViewModel = currentUserViewModel) }
        }
        composable(
            Screen.RentView.route,
            arguments = listOf(navArgument("id") { type = NavType.IntType })
        ) { backStackEntry ->
            backStackEntry.arguments?.let { RentView(it.getInt("id")) }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MainNavbar(
    isDarkTheme: MutableState<Boolean>,
    dataStoreManager: DataStoreManager
) {
    val navController = rememberNavController()
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentDestination = navBackStackEntry?.destination
    val currentScreen = currentDestination?.route?.let { Screen.getItem(it) }

    Scaffold(
        topBar = {
            Topbar(navController, currentScreen)
        },
        bottomBar = {
            if (currentScreen == null || currentScreen.showInBottomBar) {
                Navbar(navController, currentDestination)
            }
        }
    ) { innerPadding ->
        Navhost(navController, innerPadding, isDarkTheme, dataStoreManager)
    }
}
