package com.example.ops_android.ui.navigation

import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Inventory
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.ShoppingCart
import androidx.compose.material.icons.filled.Warehouse
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.navigation.NavDestination.Companion.hierarchy
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.example.ops_android.ui.auth.LoginScreen
import com.example.ops_android.ui.customer.CustomerListScreen
import com.example.ops_android.ui.home.HomeScreen
import com.example.ops_android.ui.order.OrderDetailScreen
import com.example.ops_android.ui.order.OrderFormScreen
import com.example.ops_android.ui.order.OrderListScreen
import com.example.ops_android.ui.profile.ProfileScreen
import com.example.ops_android.ui.schedule.ScheduleScreen
import com.example.ops_android.ui.search.SearchScreen
import com.example.ops_android.ui.settings.SettingsScreen
import com.example.ops_android.ui.settings.PrinterTestScreen
import com.example.ops_android.ui.warehouse.ItemDetailScreen
import com.example.ops_android.ui.warehouse.ItemFormScreen
import com.example.ops_android.ui.warehouse.WarehouseScreen
import com.example.ops_android.ui.workorder.WorkOrderDetailScreen
import com.example.ops_android.ui.workorder.WorkOrderFormScreen
import com.example.ops_android.ui.workorder.WorkOrderListScreen

object Routes {
    const val LOGIN = "login"
    const val MAIN = "main"
    const val SETTINGS = "settings"
    const val SEARCH = "search"
    const val SCHEDULE = "schedule"
    const val ORDER_DETAIL = "order_detail/{orderId}"
    const val ORDER_FORM = "order_form?editId={editId}"
    const val WORK_ORDER_DETAIL = "work_order_detail/{id}"
    const val WORK_ORDER_FORM = "work_order_form?editId={editId}&prefillItemId={prefillItemId}"
    const val ITEM_DETAIL = "item_detail/{id}"
    const val ITEM_FORM = "item_form/{containerId}?editId={editId}"
    const val CUSTOMER_LIST = "customer_list"
    const val PRINTER_TEST = "printer_test"

    fun orderDetail(orderId: Int) = "order_detail/$orderId"
    fun orderForm(editId: Int? = null) = if (editId != null) "order_form?editId=$editId" else "order_form"
    fun workOrderDetail(id: Int) = "work_order_detail/$id"
    fun workOrderForm(editId: Int? = null, prefillItemId: Int = -1) =
        "work_order_form?editId=${editId ?: -1}&prefillItemId=$prefillItemId"
    fun itemDetail(id: Int) = "item_detail/$id"
    fun itemForm(containerId: Int, editId: Int? = null) = if (editId != null) "item_form/$containerId?editId=$editId" else "item_form/$containerId"
}

object BottomTabs {
    const val HOME = "home"
    const val ORDERS = "orders"
    const val WORK_ORDERS = "work_orders"
    const val WAREHOUSE = "warehouse"
    const val PROFILE = "profile"
}

data class BottomNavItem(val route: String, val icon: ImageVector, val label: String)

val bottomNavItems = listOf(
    BottomNavItem(BottomTabs.HOME, Icons.Default.Home, "首页"),
    BottomNavItem(BottomTabs.ORDERS, Icons.Default.ShoppingCart, "订单"),
    BottomNavItem(BottomTabs.WORK_ORDERS, Icons.Default.Inventory, "工单"),
    BottomNavItem(BottomTabs.WAREHOUSE, Icons.Default.Warehouse, "仓库"),
    BottomNavItem(BottomTabs.PROFILE, Icons.Default.Person, "我的")
)

@Composable
fun OPSNavGraph(isLoggedIn: Boolean) {
    val rootNavController = rememberNavController()

    NavHost(navController = rootNavController, startDestination = if (isLoggedIn) Routes.MAIN else Routes.LOGIN) {
        composable(Routes.LOGIN) {
            LoginScreen(
                onLoginSuccess = { rootNavController.navigate(Routes.MAIN) { popUpTo(Routes.LOGIN) { inclusive = true } } },
                onGoToSettings = { rootNavController.navigate(Routes.SETTINGS) }
            )
        }
        composable(Routes.MAIN) {
            MainScreen(
                onLogout = { rootNavController.navigate(Routes.LOGIN) { popUpTo(Routes.MAIN) { inclusive = true } } },
                onNavigate = { route -> rootNavController.navigate(route) }
            )
        }
        composable(Routes.SETTINGS) {
            SettingsScreen(
                onBack = { rootNavController.popBackStack() },
                onPrinterTest = { rootNavController.navigate(Routes.PRINTER_TEST) }
            )
        }
        composable(Routes.PRINTER_TEST) {
            PrinterTestScreen(onBack = { rootNavController.popBackStack() })
        }
        composable(Routes.SEARCH) {
            SearchScreen(
                onOrderClick = { id -> rootNavController.navigate(Routes.orderDetail(id)) },
                onWorkOrderClick = { id -> rootNavController.navigate(Routes.workOrderDetail(id)) },
                onItemClick = { id -> rootNavController.navigate(Routes.itemDetail(id)) },
                onContainerClick = { id -> rootNavController.navigate(Routes.MAIN) },
                onBack = { rootNavController.popBackStack() }
            )
        }
        composable(Routes.SCHEDULE) {
            ScheduleScreen(onBack = { rootNavController.popBackStack() })
        }
        composable(Routes.ORDER_DETAIL, arguments = listOf(navArgument("orderId") { type = NavType.IntType })) { backStackEntry ->
            val orderId = backStackEntry.arguments?.getInt("orderId") ?: return@composable
            OrderDetailScreen(orderId = orderId, onBack = { rootNavController.popBackStack() })
        }
        composable(Routes.ORDER_FORM, arguments = listOf(navArgument("editId") { type = NavType.IntType; defaultValue = -1 })) { backStackEntry ->
            val editId = backStackEntry.arguments?.getInt("editId")?.takeIf { it > 0 }
            OrderFormScreen(editOrderId = editId, onBack = { rootNavController.popBackStack() }, onSaved = { rootNavController.popBackStack() })
        }
        composable(Routes.WORK_ORDER_DETAIL, arguments = listOf(navArgument("id") { type = NavType.IntType })) { backStackEntry ->
            val id = backStackEntry.arguments?.getInt("id") ?: return@composable
            WorkOrderDetailScreen(id = id, onBack = { rootNavController.popBackStack() })
        }
        composable(Routes.WORK_ORDER_FORM, arguments = listOf(
            navArgument("editId") { type = NavType.IntType; defaultValue = -1 },
            navArgument("prefillItemId") { type = NavType.IntType; defaultValue = -1 }
        )) { backStackEntry ->
            val editId = backStackEntry.arguments?.getInt("editId")?.takeIf { it > 0 }
            val prefillItemId = backStackEntry.arguments?.getInt("prefillItemId")?.takeIf { it > 0 }
            WorkOrderFormScreen(editId = editId, prefillItemId = prefillItemId, onBack = { rootNavController.popBackStack() }, onSaved = { rootNavController.popBackStack() })
        }
        composable(Routes.ITEM_DETAIL, arguments = listOf(navArgument("id") { type = NavType.IntType })) { backStackEntry ->
            val id = backStackEntry.arguments?.getInt("id") ?: return@composable
            ItemDetailScreen(id = id, onBack = { rootNavController.popBackStack() },
                onCreateWorkOrder = { itemId -> rootNavController.navigate(Routes.workOrderForm(prefillItemId = itemId)) },
                onWorkOrderClick = { woId -> rootNavController.navigate(Routes.workOrderDetail(woId)) })
        }
        composable(Routes.ITEM_FORM, arguments = listOf(navArgument("containerId") { type = NavType.IntType }, navArgument("editId") { type = NavType.IntType; defaultValue = -1 })) { backStackEntry ->
            val containerId = backStackEntry.arguments?.getInt("containerId") ?: 0
            val editId = backStackEntry.arguments?.getInt("editId")?.takeIf { it > 0 }
            ItemFormScreen(containerId = containerId, editId = editId, onBack = { rootNavController.popBackStack() }, onSaved = { rootNavController.popBackStack() })
        }
        composable(Routes.CUSTOMER_LIST) {
            CustomerListScreen(onBack = { rootNavController.popBackStack() })
        }
    }
}

@Composable
fun MainScreen(onLogout: () -> Unit, onNavigate: (String) -> Unit) {
    val tabNavController = rememberNavController()

    Scaffold(
        bottomBar = {
            NavigationBar {
                val navBackStackEntry by tabNavController.currentBackStackEntryAsState()
                val currentDestination = navBackStackEntry?.destination
                bottomNavItems.forEach { item ->
                    NavigationBarItem(
                        icon = { Icon(item.icon, contentDescription = item.label) },
                        label = { Text(item.label) },
                        selected = currentDestination?.hierarchy?.any { it.route == item.route } == true,
                        onClick = {
                            tabNavController.navigate(item.route) {
                                popUpTo(tabNavController.graph.findStartDestination().id) { saveState = true }
                                launchSingleTop = true
                                restoreState = true
                            }
                        }
                    )
                }
            }
        }
    ) { innerPadding ->
        NavHost(navController = tabNavController, startDestination = BottomTabs.HOME, modifier = Modifier.padding(innerPadding)) {
            composable(BottomTabs.HOME) {
                HomeScreen(
                    onSearchClick = { onNavigate(Routes.SEARCH) },
                    onScheduleClick = { onNavigate(Routes.SCHEDULE) }
                )
            }
            composable(BottomTabs.ORDERS) {
                OrderListScreen(
                    onOrderClick = { id -> onNavigate(Routes.orderDetail(id)) },
                    onAddClick = { onNavigate(Routes.orderForm()) }
                )
            }
            composable(BottomTabs.WORK_ORDERS) {
                WorkOrderListScreen(
                    onWorkOrderClick = { id -> onNavigate(Routes.workOrderDetail(id)) },
                    onAddClick = { onNavigate(Routes.workOrderForm()) }
                )
            }
            composable(BottomTabs.WAREHOUSE) {
                WarehouseScreen(
                    onItemClick = { id -> onNavigate(Routes.itemDetail(id)) },
                    onAddItemClick = { containerId -> onNavigate(Routes.itemForm(containerId)) }
                )
            }
            composable(BottomTabs.PROFILE) {
                ProfileScreen(
                    onLogout = onLogout,
                    onGoToSettings = { onNavigate(Routes.SETTINGS) }
                )
            }
        }
    }
}
