package com.tsmobile.app.ui.navigation

import androidx.activity.compose.BackHandler
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.tsmobile.app.MainActivity
import com.tsmobile.app.data.ConnectionState
import com.tsmobile.app.data.Repository
import com.tsmobile.app.ui.components.PokeNotification
import com.tsmobile.app.ui.components.ReconnectOverlay
import com.tsmobile.app.ui.screens.ChannelListScreen
import com.tsmobile.app.ui.screens.ChatScreen
import com.tsmobile.app.ui.screens.KickedScreen
import com.tsmobile.app.ui.screens.ServerConfigScreen
import com.tsmobile.app.viewmodel.ChannelViewModel
import com.tsmobile.app.viewmodel.ChatViewModel
import com.tsmobile.app.viewmodel.ServerViewModel
import com.tsmobile.app.viewmodel.VoiceViewModel
import kotlinx.coroutines.flow.StateFlow

/**
 * 导航路由定义。
 *
 * 路由列表：
 * - "server_config" — 服务器配置页（起始页）
 * - "channel_list" — 频道列表页（连接成功后）
 * - "chat" — 聊天页
 */
object Routes {
    const val SERVER_CONFIG = "server_config"
    const val CHANNEL_LIST = "channel_list"
    const val CHAT = "chat"
    const val KICKED = "kicked"
}

@Composable
fun AppNavGraph(
    navController: NavHostController,
    serverViewModel: ServerViewModel = viewModel(),
    channelViewModel: ChannelViewModel = viewModel(),
    chatViewModel: ChatViewModel = viewModel(),
    voiceViewModel: VoiceViewModel = viewModel(),
    deepLinkAction: StateFlow<MainActivity.DeepLinkAction?>? = null,
    onDeepLinkConsumed: (() -> Unit)? = null,
) {
    // 设置 ViewModel 引用，用于事件协调
    LaunchedEffect(Unit) {
        serverViewModel.channelViewModel = channelViewModel
        serverViewModel.chatViewModel = chatViewModel
        serverViewModel.voiceViewModel = voiceViewModel
        channelViewModel.chatViewModel = chatViewModel
    }

    // 观察连接状态变化，处理导航
    val connectionState by serverViewModel.connectionState.collectAsState()

    // ── 系统通知 deep link 导航 ──
    // 当通知点击时，MainActivity 将目标写入 deepLinkAction，
    // 等待连接状态为 Connected 后执行导航。
    val deepLink by (deepLinkAction?.collectAsState() ?: remember { mutableStateOf(null) })
    LaunchedEffect(deepLink, connectionState) {
        val action = deepLink ?: return@LaunchedEffect
        if (connectionState !is ConnectionState.Connected) return@LaunchedEffect

        when (action.target) {
            MainActivity.DEEP_LINK_CHAT -> {
                // 先跳到频道列表（清空回退栈），再进入聊天页
                navController.navigate(Routes.CHANNEL_LIST) {
                    popUpTo(Routes.SERVER_CONFIG) { inclusive = true }
                }
                navController.navigate(Routes.CHAT) {
                    launchSingleTop = true
                }
            }
            MainActivity.DEEP_LINK_CHANNEL_LIST -> {
                navController.navigate(Routes.CHANNEL_LIST) {
                    popUpTo(Routes.SERVER_CONFIG) { inclusive = true }
                }
            }
        }
        onDeepLinkConsumed?.invoke()
    }

    LaunchedEffect(connectionState) {
        when (val state = connectionState) {
            is ConnectionState.Disconnected -> {
                if (state.wasKicked) {
                    navController.navigate(Routes.KICKED) {
                        popUpTo(Routes.CHANNEL_LIST) { inclusive = true }
                    }
                } else {
                    // 普通断开（重连失败/放弃）→ 返回主页
                    navController.navigate(Routes.SERVER_CONFIG) {
                        popUpTo(Routes.CHANNEL_LIST) { inclusive = true }
                    }
                }
            }
            is ConnectionState.Connected -> {
                // 重连成功 → 确保在频道列表页
                if (navController.currentDestination?.route == Routes.KICKED) {
                    navController.navigate(Routes.CHANNEL_LIST) {
                        popUpTo(Routes.KICKED) { inclusive = true }
                    }
                }
            }
            else -> { /* 其他状态不处理导航 */ }
        }
    }

    // 全局 Poke 气泡通知（覆盖在所有页面上方）
    val showPokeNotification by serverViewModel.showPokeNotification.collectAsState()
    val pokeNotification by serverViewModel.pokeNotification.collectAsState()

    Box(modifier = Modifier.fillMaxSize()) {
        NavHost(
            navController = navController,
            startDestination = Routes.SERVER_CONFIG,
            // 禁用默认的淡入淡出动画，避免页面切换显得迟钝
            enterTransition = { EnterTransition.None },
            exitTransition = { ExitTransition.None },
            popEnterTransition = { EnterTransition.None },
            popExitTransition = { ExitTransition.None },
        ) {
            // 服务器配置页
            composable(Routes.SERVER_CONFIG) {
                ServerConfigScreen(
                    viewModel = serverViewModel,
                    onNavigateToChannelList = {
                        navController.navigate(Routes.CHANNEL_LIST) {
                            popUpTo(Routes.SERVER_CONFIG) { inclusive = true }
                        }
                    },
                )
            }

            // 频道列表页
            composable(Routes.CHANNEL_LIST) {
                ChannelListScreen(
                    channelViewModel = channelViewModel,
                    voiceViewModel = voiceViewModel,
                    serverViewModel = serverViewModel,
                    onNavigateToChat = {
                        if (navController.currentDestination?.route == Routes.CHANNEL_LIST) {
                            navController.navigate(Routes.CHAT) {
                                launchSingleTop = true
                            }
                        }
                    },
                    onNavigateToServerConfig = {
                        serverViewModel.disconnect()
                        navController.navigate(Routes.SERVER_CONFIG) {
                            popUpTo(Routes.CHANNEL_LIST) { inclusive = true }
                        }
                    },
                )
            }

            // 聊天页
            composable(Routes.CHAT) {
                // 进入聊天页：加载当前频道的消息
                val currentChannelId by channelViewModel.currentChannelId.collectAsState()
                LaunchedEffect(currentChannelId) {
                    var channelIdLong = currentChannelId.toLongOrNull() ?: 0L
                    // 备用方案：如果 Repository.currentChannelId 为 "0"（GetChannelID 失败），
                    // 从客户端列表中获取自身所在的频道 ID
                    if (channelIdLong <= 0L) {
                        channelIdLong = Repository.getSelfChannelId().toLongOrNull() ?: 0L
                    }
                    if (channelIdLong > 0L) {
                        chatViewModel.enterChat(2, channelIdLong)
                    }
                }

                val leaveChat = {
                    if (navController.currentDestination?.route == Routes.CHAT &&
                        navController.popBackStack(Routes.CHANNEL_LIST, inclusive = false)
                    ) {
                        chatViewModel.leaveChat()
                    }
                }
                BackHandler(onBack = leaveChat)

                ChatScreen(
                    chatViewModel = chatViewModel,
                    channelViewModel = channelViewModel,
                    voiceViewModel = voiceViewModel,
                    serverViewModel = serverViewModel,
                    onNavigateBack = leaveChat,
                    onOpenChannelDetail = { channelId ->
                        channelViewModel.openChannelDetailCard(channelId)
                    },
                )
            }

            // 被踢页面
            composable(Routes.KICKED) {
                val kickReason by serverViewModel.kickReason.collectAsState()
                KickedScreen(
                    reason = kickReason,
                    onReconnect = { serverViewModel.reconnectAfterKick() },
                    onBackToHome = {
                        serverViewModel.backToHome()
                        navController.navigate(Routes.SERVER_CONFIG) {
                            popUpTo(Routes.KICKED) { inclusive = true }
                        }
                    },
                )
            }
        }

        // 重连全屏遮罩（阻止用户操作，覆盖所有页面包括聊天页）
        val connState = connectionState
        if (connState is ConnectionState.WaitingForNetwork ||
            connState is ConnectionState.Reconnecting
        ) {
            ReconnectOverlay(
                connectionState = connState,
                onAbandon = { serverViewModel.abandonReconnect() },
            )
        }

        // Poke 气泡通知（全局覆盖层）
        PokeNotification(
            pokeEvent = pokeNotification,
            isVisible = showPokeNotification,
            onDismiss = { serverViewModel.dismissPokeNotification() },
        )
    }
}

