package com.safecheckin.app.ui

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.Info
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.safecheckin.app.data.api.ApiClient
import com.safecheckin.app.ui.screens.about.AboutScreen
import com.safecheckin.app.ui.screens.auth.AuthViewModel
import com.safecheckin.app.ui.screens.auth.ForgotPasswordScreen
import com.safecheckin.app.ui.screens.auth.LoginScreen
import com.safecheckin.app.ui.screens.auth.RegisterScreen
import com.safecheckin.app.ui.screens.contacts.ContactsScreen
import com.safecheckin.app.ui.screens.contacts.ContactsViewModel
import com.safecheckin.app.ui.screens.home.HomeScreen
import com.safecheckin.app.ui.screens.home.HomeViewModel
import com.safecheckin.app.ui.screens.settings.SettingsScreen
import com.safecheckin.app.ui.screens.settings.SettingsViewModel
import com.safecheckin.app.ui.theme.SafeCheckInTheme

sealed class Screen(val route: String, val title: String, val icon: androidx.compose.ui.graphics.vector.ImageVector) {
    object Login : Screen("login", "登录", Icons.Default.Person)
    object Register : Screen("register", "注册", Icons.Default.Person)
    object ForgotPassword : Screen("forgot_password", "忘记密码", Icons.Default.Person)
    object Home : Screen("home", "状态", Icons.Default.Home)
    object Contacts : Screen("contacts", "联系人", Icons.Default.Person)
    object Settings : Screen("settings", "设置", Icons.Default.Settings)
    object About : Screen("about", "关于", Icons.Default.Info)
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SafeCheckInApp() {
    val navController = rememberNavController()
    val context = LocalContext.current
    val apiClient = remember { ApiClient(context) }

    // 监听登录状态
    val isLoggedIn by apiClient.isLoggedIn.collectAsState(initial = false)

    val items = listOf(Screen.Home, Screen.Contacts, Screen.Settings, Screen.About)

    SafeCheckInTheme {
        Scaffold(
            bottomBar = {
                // 只在登录后显示底部导航
                if (isLoggedIn) {
                    NavigationBar {
                        val navBackStackEntry by navController.currentBackStackEntryAsState()
                        val currentDestination = navBackStackEntry?.destination

                        items.forEach { screen ->
                            NavigationBarItem(
                                icon = { Icon(screen.icon, contentDescription = screen.title) },
                                label = { Text(screen.title) },
                                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
                                    }
                                }
                            )
                        }
                    }
                }
            }
        ) { innerPadding ->
            NavHost(
                navController = navController,
                startDestination = if (isLoggedIn) Screen.Home.route else Screen.Login.route,
                modifier = Modifier.padding(innerPadding)
            ) {
                // 登录页面
                composable(Screen.Login.route) {
                    val viewModel: AuthViewModel = viewModel(
                        factory = AuthViewModel.Factory(apiClient)
                    )
                    LoginScreen(
                        viewModel = viewModel,
                        onNavigateToRegister = {
                            navController.navigate(Screen.Register.route)
                        },
                        onNavigateToForgotPassword = {
                            navController.navigate(Screen.ForgotPassword.route)
                        },
                        onLoginSuccess = {
                            navController.navigate(Screen.Home.route) {
                                popUpTo(Screen.Login.route) { inclusive = true }
                            }
                        }
                    )
                }

                // 注册页面
                composable(Screen.Register.route) {
                    val viewModel: AuthViewModel = viewModel(
                        factory = AuthViewModel.Factory(apiClient)
                    )
                    RegisterScreen(
                        viewModel = viewModel,
                        onNavigateToLogin = {
                            navController.navigate(Screen.Login.route) {
                                popUpTo(Screen.Register.route) { inclusive = true }
                            }
                        },
                        onRegisterSuccess = {
                            navController.navigate(Screen.Home.route) {
                                popUpTo(Screen.Register.route) { inclusive = true }
                            }
                        }
                    )
                }

                // 忘记密码页面
                composable(Screen.ForgotPassword.route) {
                    val viewModel: AuthViewModel = viewModel(
                        factory = AuthViewModel.Factory(apiClient)
                    )
                    ForgotPasswordScreen(
                        viewModel = viewModel,
                        onNavigateBack = {
                            navController.popBackStack()
                        },
                        onResetSuccess = {
                            navController.navigate(Screen.Login.route) {
                                popUpTo(Screen.ForgotPassword.route) { inclusive = true }
                            }
                        }
                    )
                }

                // 主页 — 使用云端 ViewModel
                composable(Screen.Home.route) {
                    val viewModel: HomeViewModel = viewModel(
                        factory = HomeViewModel.Factory(context)
                    )
                    HomeScreen(viewModel = viewModel)
                }

                // 联系人 — 使用云端 ViewModel
                composable(Screen.Contacts.route) {
                    val viewModel: ContactsViewModel = viewModel(
                        factory = ContactsViewModel.Factory(context)
                    )
                    ContactsScreen(viewModel = viewModel)
                }

                // 设置 — 使用云端 ViewModel，退出时清除登录态并跳转
                composable(Screen.Settings.route) {
                    val authViewModel: AuthViewModel = viewModel(
                        factory = AuthViewModel.Factory(apiClient)
                    )
                    val settingsViewModel: SettingsViewModel = viewModel(
                        factory = SettingsViewModel.Factory(context)
                    )
                    SettingsScreen(
                        viewModel = settingsViewModel,
                        onLogout = {
                            authViewModel.logout()
                            navController.navigate(Screen.Login.route) {
                                popUpTo(0) { inclusive = true }
                            }
                        },
                        onDeleteAccount = {
                            settingsViewModel.deleteAccount {
                                authViewModel.logout()
                                navController.navigate(Screen.Login.route) {
                                    popUpTo(0) { inclusive = true }
                                }
                            }
                        }
                    )
                }

                // 关于
                composable(Screen.About.route) {
                    AboutScreen()
                }
            }
        }
    }
}
