package com.omixlab.lckcontrol.ui.navigation

import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Dashboard
import androidx.compose.material.icons.filled.Devices
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.Icon
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.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.navigation.NavGraph.Companion.findStartDestination
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.omixlab.lckcontrol.data.local.TokenStore
import com.omixlab.lckcontrol.data.remote.LckApiService
import com.omixlab.lckcontrol.ui.accounts.AccountsScreen
import com.omixlab.lckcontrol.ui.clients.ActiveClientsScreen
import com.omixlab.lckcontrol.ui.dashboard.DashboardScreen
import com.omixlab.lckcontrol.ui.login.LoginScreen
import com.omixlab.lckcontrol.ui.chat.ChatScreen
import com.omixlab.lckcontrol.ui.plans.CreatePlanScreen
import com.omixlab.lckcontrol.ui.plans.PlanDetailScreen

private data class BottomNavItem(
    val screen: Screen,
    val label: String,
    val icon: ImageVector,
)

private val bottomNavItems = listOf(
    BottomNavItem(Screen.Dashboard, "Dashboard", Icons.Default.Dashboard),
    BottomNavItem(Screen.Accounts, "Accounts", Icons.Default.Person),
    BottomNavItem(Screen.ActiveClients, "Clients", Icons.Default.Devices),
)

@Composable
fun AppNavigation(tokenStore: TokenStore, apiService: LckApiService) {
    val navController = rememberNavController()
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    val currentRoute = navBackStackEntry?.destination?.route

    val showBottomBar = currentRoute in bottomNavItems.map { it.screen.route }
    val startDestination = if (tokenStore.isLoggedIn()) Screen.Dashboard.route else Screen.Login.route

    // Session validation on app open — if we think we're logged in, verify it
    LaunchedEffect(Unit) {
        if (tokenStore.isLoggedIn()) {
            try {
                apiService.getMe()
            } catch (_: Exception) {
                // AuthInterceptor will try refresh; if that also fails, session is invalid
                if (!tokenStore.isLoggedIn()) {
                    navController.navigate(Screen.Login.route) {
                        popUpTo(0) { inclusive = true }
                    }
                }
            }
        }
    }

    Scaffold(
        bottomBar = {
            if (showBottomBar) {
                NavigationBar {
                    bottomNavItems.forEach { item ->
                        NavigationBarItem(
                            icon = {
                                Icon(item.icon, contentDescription = item.label)
                            },
                            label = { Text(item.label) },
                            selected = currentRoute == item.screen.route,
                            onClick = {
                                navController.navigate(item.screen.route) {
                                    popUpTo(navController.graph.findStartDestination().id) {
                                        saveState = true
                                    }
                                    launchSingleTop = true
                                    restoreState = true
                                }
                            },
                        )
                    }
                }
            }
        },
    ) { innerPadding ->
        NavHost(
            navController = navController,
            startDestination = startDestination,
            modifier = Modifier.padding(innerPadding),
        ) {
            composable(Screen.Login.route) {
                LoginScreen(
                    onLoginSuccess = {
                        navController.navigate(Screen.Dashboard.route) {
                            popUpTo(Screen.Login.route) { inclusive = true }
                        }
                    },
                )
            }
            composable(Screen.Dashboard.route) {
                DashboardScreen(
                    onNavigateToCreatePlan = { navController.navigate(Screen.CreatePlan.createRoute()) },
                    onNavigateToPlan = { planId ->
                        navController.navigate(Screen.PlanDetail.createRoute(planId))
                    },
                    onNavigateToChat = { planId, service, destinationId ->
                        navController.navigate(Screen.Chat.createRoute(planId, service, destinationId))
                    },
                )
            }
            composable(Screen.Accounts.route) {
                AccountsScreen()
            }
            composable(
                route = Screen.CreatePlan.route,
                arguments = listOf(navArgument("planId") {
                    type = NavType.StringType
                    nullable = true
                    defaultValue = null
                }),
            ) {
                CreatePlanScreen(
                    onPlanCreated = { planId ->
                        navController.navigate(Screen.PlanDetail.createRoute(planId)) {
                            popUpTo(Screen.Dashboard.route)
                        }
                    },
                    onBack = { navController.popBackStack() },
                )
            }
            composable(
                route = Screen.PlanDetail.route,
                arguments = listOf(navArgument("planId") { type = NavType.StringType }),
            ) { backStackEntry ->
                val planId = backStackEntry.arguments?.getString("planId") ?: return@composable
                PlanDetailScreen(
                    planId = planId,
                    onBack = { navController.popBackStack() },
                    onNavigateToEditPlan = { id ->
                        navController.navigate(Screen.CreatePlan.createRoute(id))
                    },
                )
            }
            composable(
                route = Screen.Chat.route,
                arguments = listOf(
                    navArgument("planId") { type = NavType.StringType },
                    navArgument("service") { type = NavType.StringType },
                    navArgument("destinationId") { type = NavType.StringType },
                ),
            ) {
                ChatScreen(onBack = { navController.popBackStack() })
            }
            composable(Screen.ActiveClients.route) {
                ActiveClientsScreen(
                    onNavigateToPlan = { planId ->
                        navController.navigate(Screen.PlanDetail.createRoute(planId))
                    },
                )
            }
        }
    }
}
