package com.jishisongfu.duobibi.ui.nav

import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Balance
import androidx.compose.material.icons.filled.Explore
import androidx.compose.material.icons.filled.Lightbulb
import androidx.compose.material.icons.filled.NotificationsActive
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.outlined.Balance
import androidx.compose.material.icons.outlined.Explore
import androidx.compose.material.icons.outlined.Lightbulb
import androidx.compose.material.icons.outlined.Notifications
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
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.jishisongfu.duobibi.ui.alert.AlertScreen
import com.jishisongfu.duobibi.ui.arena.ArenaScreen
import com.jishisongfu.duobibi.ui.arena.ArenaViewModel
import com.jishisongfu.duobibi.ui.detail.ProductDetailScreen
import com.jishisongfu.duobibi.ui.discover.DiscoverScreen
import com.jishisongfu.duobibi.ui.mine.AboutScreen
import com.jishisongfu.duobibi.ui.mine.DiagnosticsScreen
import com.jishisongfu.duobibi.ui.mine.MineScreen
import com.jishisongfu.duobibi.ui.privacy.PrivacyPolicyScreen
import com.jishisongfu.duobibi.ui.records.ClusterDetailScreen
import com.jishisongfu.duobibi.ui.records.NewRecordScreen
import com.jishisongfu.duobibi.ui.records.RecordsScreen
import com.jishisongfu.duobibi.ui.theme.DbbColors
import com.jishisongfu.duobibi.ui.tools.BundleCalculatorScreen
import com.jishisongfu.duobibi.ui.tools.InstallmentCalculatorScreen
import com.jishisongfu.duobibi.ui.tools.UnitPriceCalculatorScreen
import com.jishisongfu.duobibi.ui.watched.WatchedProductsScreen
import com.jishisongfu.duobibi.ui.worth.WorthBuyScreen

private object Routes {
    // 5 个底部 Tab(v1.1:把 RECORDS 挤出 Tab,新增 DISCOVER 作为新首屏)
    const val DISCOVER = "discover"
    const val ARENA = "arena"
    const val ALERT = "alert"
    const val WORTH = "worth"
    const val MINE = "mine"

    // 非 Tab 路由(从其它入口可达)
    const val RECORDS = "records"
    const val CLUSTER = "cluster/{id}"
    const val NEW_RECORD = "new_record"
    const val DIAGNOSTICS = "diagnostics"
    const val ABOUT = "about"
    const val PRIVACY = "privacy"
    const val TOOL_UNIT = "tool_unit"
    const val TOOL_BUNDLE = "tool_bundle"
    const val TOOL_INSTALLMENT = "tool_installment"

    // v1.2:Discover 卡片点进的商品详情页(纵深层级,区别于 Arena 的横向搜索)
    const val PRODUCT_DETAIL = "product/{itemId}"

    // v1.3:发现页 hero 右上 ❤️ 入口跳的关注列表
    const val WATCHED = "watched"

    fun cluster(id: Long) = "cluster/$id"
    fun productDetail(itemId: String) = "product/$itemId"
}

private val TABS = setOf(Routes.DISCOVER, Routes.ARENA, Routes.ALERT, Routes.WORTH, Routes.MINE)

@Composable
fun AppNavHost() {
    val nav = rememberNavController()
    val backStackEntry by nav.currentBackStackEntryAsState()
    val current = backStackEntry?.destination?.route
    val showBar = current in TABS

    // ArenaViewModel 上提到整个 NavHost 作用域 —— Discover 卡片要把 title/category
    // 喂给同一个 ArenaViewModel 实例再跳过去,避免两个 Tab 各自一份导致状态不同步。
    val arenaVm: ArenaViewModel = hiltViewModel()

    Scaffold(
        bottomBar = { if (showBar) BottomBar(current) { route -> nav.navigateTab(route) } },
        contentWindowInsets = WindowInsets(0),
    ) { padding ->
        NavHost(
            navController = nav,
            startDestination = Routes.DISCOVER,
            modifier = Modifier.padding(padding),
        ) {
            composable(Routes.DISCOVER) {
                DiscoverScreen(
                    onOpenDetail = { id -> nav.navigate(Routes.productDetail(id)) },
                    onOpenWatched = { nav.navigate(Routes.WATCHED) },
                )
            }
            composable(Routes.ARENA) {
                ArenaScreen(
                    onOpenCluster = { nav.navigate(Routes.cluster(it)) },
                    vm = arenaVm,
                )
            }
            composable(Routes.ALERT) { AlertScreen() }
            composable(Routes.WORTH) {
                WorthBuyScreen(
                    onOpenCluster = { nav.navigate(Routes.cluster(it)) },
                    onOpenArena = { title ->
                        arenaVm.submitWithTitle(title, null)
                        nav.navigateTab(Routes.ARENA)
                    },
                )
            }
            composable(Routes.MINE) {
                MineScreen(
                    onOpenUnitPrice = { nav.navigate(Routes.TOOL_UNIT) },
                    onOpenBundle = { nav.navigate(Routes.TOOL_BUNDLE) },
                    onOpenInstallment = { nav.navigate(Routes.TOOL_INSTALLMENT) },
                    onOpenDiagnostics = { nav.navigate(Routes.DIAGNOSTICS) },
                    onOpenAbout = { nav.navigate(Routes.ABOUT) },
                    onOpenPrivacy = { nav.navigate(Routes.PRIVACY) },
                    onOpenRecords = { nav.navigate(Routes.RECORDS) },
                )
            }

            // 非 Tab,从 Discover hero 右上 ❤️ 跳进的关注列表
            composable(Routes.WATCHED) {
                WatchedProductsScreen(
                    onBack = { nav.popBackStack() },
                    onOpenDetail = { id -> nav.navigate(Routes.productDetail(id)) },
                )
            }

            // 非 Tab,从 Discover 卡片跳进的商品详情(纵深一层)
            composable(
                Routes.PRODUCT_DETAIL,
                arguments = listOf(navArgument("itemId") { type = NavType.StringType }),
            ) { entry ->
                val id = entry.arguments?.getString("itemId") ?: return@composable
                ProductDetailScreen(
                    itemId = id,
                    onBack = { nav.popBackStack() },
                    onOpenArena = { title ->
                        arenaVm.submitWithTitle(title, null)
                        nav.navigateTab(Routes.ARENA)
                    },
                    onAddAlert = { title, target -> arenaVm.addToAlert(title, target) {} },
                    onOpenDetail = { otherId -> nav.navigate(Routes.productDetail(otherId)) },
                )
            }

            // 非 Tab,从 Mine 跳进
            composable(Routes.RECORDS) {
                RecordsScreen(
                    onOpenCluster = { nav.navigate(Routes.cluster(it)) },
                    onAdd = { nav.navigate(Routes.NEW_RECORD) },
                )
            }
            composable(
                Routes.CLUSTER,
                arguments = listOf(navArgument("id") { type = NavType.LongType }),
            ) { entry ->
                val id = entry.arguments?.getLong("id") ?: return@composable
                ClusterDetailScreen(clusterId = id, onBack = { nav.popBackStack() })
            }
            composable(Routes.NEW_RECORD) { NewRecordScreen(onBack = { nav.popBackStack() }) }
            composable(Routes.DIAGNOSTICS) { DiagnosticsScreen(onBack = { nav.popBackStack() }) }
            composable(Routes.ABOUT) {
                AboutScreen(onBack = { nav.popBackStack() }, onOpenPrivacy = { nav.navigate(Routes.PRIVACY) })
            }
            composable(Routes.PRIVACY) { PrivacyPolicyScreen(onBack = { nav.popBackStack() }) }
            composable(Routes.TOOL_UNIT) { UnitPriceCalculatorScreen(onBack = { nav.popBackStack() }) }
            composable(Routes.TOOL_BUNDLE) { BundleCalculatorScreen(onBack = { nav.popBackStack() }) }
            composable(Routes.TOOL_INSTALLMENT) { InstallmentCalculatorScreen(onBack = { nav.popBackStack() }) }
        }
    }
}

private fun NavController.navigateTab(route: String) {
    navigate(route) {
        popUpTo(graph.findStartDestination().id) { saveState = true }
        launchSingleTop = true
        restoreState = true
    }
}

@Composable
private fun BottomBar(current: String?, onSelect: (String) -> Unit) {
    NavigationBar(containerColor = MaterialTheme.colorScheme.surface) {
        Item(current == Routes.DISCOVER, "发现", Icons.Filled.Explore, Icons.Outlined.Explore) { onSelect(Routes.DISCOVER) }
        Item(current == Routes.ARENA, "比价", Icons.Filled.Balance, Icons.Outlined.Balance) { onSelect(Routes.ARENA) }
        Item(current == Routes.ALERT, "雷达", Icons.Filled.NotificationsActive, Icons.Outlined.Notifications) { onSelect(Routes.ALERT) }
        Item(current == Routes.WORTH, "值不值", Icons.Filled.Lightbulb, Icons.Outlined.Lightbulb) { onSelect(Routes.WORTH) }
        Item(current == Routes.MINE, "我的", Icons.Filled.Person, Icons.Outlined.Person) { onSelect(Routes.MINE) }
    }
}

@Composable
private fun RowScope.Item(selected: Boolean, label: String, on: ImageVector, off: ImageVector, onClick: () -> Unit) {
    NavigationBarItem(
        selected = selected,
        onClick = onClick,
        icon = { Icon(if (selected) on else off, contentDescription = label) },
        label = { Text(label, fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal) },
        colors = NavigationBarItemDefaults.colors(
            selectedIconColor = Color.White,
            selectedTextColor = DbbColors.Teal,
            indicatorColor = DbbColors.Teal,
            unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant,
            unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant,
        ),
    )
}
