package com.img.rabbit.pages

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.img.rabbit.pages.screen.mine.FeedbackScreen
import com.img.rabbit.pages.screen.mine.OnlineServiceScreen
import com.img.rabbit.pages.screen.mine.SettingScreen
import androidx.compose.material3.Icon
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.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavType
import androidx.navigation.navArgument
import com.img.rabbit.R
import com.img.rabbit.pages.screen.HomeScreen
import com.img.rabbit.pages.screen.MineScreen
import com.img.rabbit.pages.screen.make.CutoutScreen
import com.img.rabbit.pages.screen.make.FormatScreen
import com.img.rabbit.pages.screen.make.LongImageScreen
import com.img.rabbit.pages.screen.make.ResizeScreen
import com.img.rabbit.pages.screen.mine.setting.AboutScreen
import com.img.rabbit.pages.screen.mine.setting.AccountBindScreen
import com.img.rabbit.pages.screen.mine.setting.AccountManagerScreen
import com.img.rabbit.pages.screen.mine.setting.BindScreen
import com.img.rabbit.pages.screen.other.CameraGuideScreen
import com.img.rabbit.provider.storage.PreferenceUtil
import com.img.rabbit.route.ScreenRoute
import com.img.rabbit.viewmodel.BindViewModel
import com.img.rabbit.viewmodel.GeneralViewModel
import com.img.rabbit.viewmodel.LoginViewModel

// 定义底部导航的标签页
sealed class TabItem(val title: String, val normalIconRes: Int, val selectedIconRes: Int, val normalColor: Color, val selectedColor: Color) {
    object Home : TabItem("首页", R.mipmap.ic_home_normal, R.mipmap.ic_home_selected, Color(0xFFAAAAAA), Color(0xFF1A1A1A))
    object Mine : TabItem("我的", R.mipmap.ic_mine_normal, R.mipmap.ic_mine_selected, Color(0xFFAAAAAA), Color(0xFF1A1A1A))
}

@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun MainScreen(generalViewModel: GeneralViewModel, loginViewModel: LoginViewModel) {

    val navController = rememberNavController()
    val networkStatus by generalViewModel.networkStatus.observeAsState(initial = true)
    val isNavigationBarVisible by generalViewModel.isNavigationBarVisible.observeAsState(initial = true)
    val tabItems = listOf(
        TabItem.Home,
        TabItem.Mine
    )
    var selectedTab: TabItem by remember { mutableStateOf(TabItem.Home) }

    // 监听返回事件
    val currentBackStackEntry = navController.currentBackStackEntry

    LaunchedEffect(currentBackStackEntry) {
        // 当返回到MineScreen页面时执行的操作
        if (currentBackStackEntry?.destination?.route == "home") {
            // 显示TabBar
            generalViewModel.setNavigationBarVisible(true)
        }
    }

    // 网络状态监听
    LaunchedEffect(networkStatus) {
        if (!networkStatus) {
            // 网络断开时的处理
            Log.w("NetworkStatus","网络断开")
        }else{
            Log.w("NetworkStatus","网络已连接")
        }
    }

    Scaffold(
        bottomBar = {
            if (isNavigationBarVisible) {
                Box {
                    NavigationBar(
                        containerColor = Color.White,
                        contentColor = Color.Transparent
                    ) {
                        tabItems.forEachIndexed { index, item ->
                            val iconRes = if (selectedTab == tabItems[index]) {
                                item.selectedIconRes
                            } else {
                                item.normalIconRes
                            }
                            NavigationBarItem(
                                icon = {
                                    Icon(
                                        painter = painterResource(id = iconRes),
                                        contentDescription = item.title,
                                        tint = Color.Unspecified
                                    )
                                },
                                label = { Text(item.title, color = if (selectedTab == tabItems[index]) item.selectedColor else item.normalColor) },
                                selected = selectedTab == tabItems[index],
                                onClick = { selectedTab = tabItems[index] },
                                colors = NavigationBarItemDefaults.colors(
                                    indicatorColor = Color.Transparent
                                )
                            )
                        }
                    }
                    // 顶部横线
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(1.dp)
                            .background(Color.Gray.copy(alpha = 0.3f))
                    )
                }
            }
        }
    ) {
            Box(
                modifier = Modifier.fillMaxSize()
            ) {
                // 导航主机
                NavHost(
                    navController = navController,
                    startDestination = ScreenRoute.Home.route
                ) {
                    // Main页面
                    composable(ScreenRoute.Main.route) {
                        MainScreen(
                            generalViewModel = generalViewModel,
                            loginViewModel = loginViewModel
                        )
                    }

                    // Tab页面
                    composable(ScreenRoute.Home.route) {
                        HomeScreen(
                            navController = navController,
                            generalViewModel = generalViewModel
                        )
                    }
                    composable(ScreenRoute.Mine.route) {
                        MineScreen(
                            navController = navController,
                            generalViewModel = generalViewModel
                        )
                    }
                    // 抠图页面（Cutout）
                    composable(ScreenRoute.Cutout.route) {
                        CutoutScreen(navController = navController)
                    }
                    // 证件页面（Certificate）
                    composable(ScreenRoute.Resize.route) {
                        ResizeScreen(navController = navController)
                    }
                    // 格式页面（Format）
                    composable(ScreenRoute.Format.route) {
                        FormatScreen(navController = navController)
                    }
                    // 拍照指南页面（CameraGuide）
                    composable(ScreenRoute.CameraGuide.route) {
                        CameraGuideScreen(navController = navController)
                    }
                    // 长图页面（LongImage）
                    composable(ScreenRoute.LongImage.route) {
                        LongImageScreen(navController = navController)
                    }


                    // 我的页面（Mine）
                    composable(ScreenRoute.Feedback.route) {
                        FeedbackScreen(navController = navController)
                    }
                    composable(ScreenRoute.OnlineService.route) {
                        OnlineServiceScreen(navController = navController)
                    }
                    composable(ScreenRoute.Setting.route) {
                        SettingScreen(navController = navController, loginViewModel = loginViewModel)
                    }

                    // 设置页面（Setting）
                    composable(ScreenRoute.BindAccount.route) {
                        AccountBindScreen(navController = navController, loginViewModel = loginViewModel)
                    }
                    composable(ScreenRoute.ManagerAccount.route) {
                        AccountManagerScreen(navController = navController, loginViewModel = loginViewModel)
                    }
                    composable(ScreenRoute.AboutMine.route) {
                        AboutScreen(navController = navController)
                    }

                    // 登录页面（Login）
                    composable(ScreenRoute.Login.route) {
                        LoginScreen(
                            navController = navController,
                            generalViewModel = generalViewModel,
                            loginViewModel = loginViewModel,
                            isVisibilityBreak = true
                        )
                    }
                    composable(
                        route = "login?type={type}",
                        arguments = listOf(
                            navArgument("type") {
                                type = NavType.IntType
                                defaultValue = LoginViewModel.JumpLoginType.NORMAL.type
                            }
                        )
                    ) { backStackEntry ->
                        val isVisibilityBreak = when(backStackEntry.arguments?.getInt("type")){
                            LoginViewModel.JumpLoginType.FROM_ADD.type -> {
                                // 添加账号
                                true
                            }
                            LoginViewModel.JumpLoginType.FROM_LOGOUT.type -> {
                                // 退出登录
                                false
                            }
                            else -> false
                        }
                        LoginScreen(
                            navController = navController,
                            generalViewModel = generalViewModel,
                            loginViewModel = loginViewModel,
                            isVisibilityBreak = isVisibilityBreak
                        )
                    }

                    // 绑定页面（Bind）
                    /*
                    composable(ScreenRoute.Bind.route) {
                        BindScreen(
                            navController = navController,
                            generalViewModel = generalViewModel,
                            bindType = BindViewModel.BindType.FROM_PHONE.type
                        )
                    }
                     */
                    composable(
                        route = "bind?type={type}",
                        arguments = listOf(
                            navArgument("type") {
                                type = NavType.IntType
                                defaultValue = BindViewModel.BindType.FROM_PHONE.type
                            }
                        )
                    ) { backStackEntry ->
                        BindScreen(
                            navController = navController,
                            generalViewModel = generalViewModel,
                            bindType = backStackEntry.arguments?.getInt("type")?:BindViewModel.BindType.FROM_PHONE.type
                        )
                    }
                }
                
                // 根据选中的Tab切换导航路由
                LaunchedEffect(selectedTab) {
                    when (selectedTab) {
                        TabItem.Home -> navController.navigate(ScreenRoute.Home.route) {
                            popUpTo(ScreenRoute.Home.route) { inclusive = true }
                        }
                        TabItem.Mine -> navController.navigate(ScreenRoute.Mine.route) {
                            popUpTo(ScreenRoute.Mine.route) { inclusive = true }
                        }
                    }
                }
            }
    }
}