package com.aiosman.ravenow.ui.index

import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
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.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemColors
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.GuestLoginCheckOut
import com.aiosman.ravenow.GuestLoginCheckOutScene
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.Messaging
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.index.tabs.add.AddPage
import com.aiosman.ravenow.ui.index.tabs.ai.Agent
import com.aiosman.ravenow.ui.index.tabs.message.NotificationsScreen
import com.aiosman.ravenow.ui.index.tabs.moment.MomentsList
import com.aiosman.ravenow.ui.index.tabs.profile.ProfileWrap
import com.aiosman.ravenow.ui.index.tabs.search.DiscoverScreen
import com.aiosman.ravenow.ui.index.tabs.shorts.ShortVideo
import com.aiosman.ravenow.ui.index.tabs.street.StreetPage
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.post.NewPostViewModel
import com.aiosman.ravenow.utils.ResourceCleanupManager
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable
fun IndexScreen() {
    val AppColors = LocalAppTheme.current
    val model = IndexViewModel
    val navigationBarHeight = with(LocalDensity.current) {
        WindowInsets.navigationBars.getBottom(this).toDp()
    }
    val navController = LocalNavController.current
    val item = listOf(
        NavigationItem.Home,
        //NavigationItem.Dynamic,
        NavigationItem.Ai,
        NavigationItem.Add,
        NavigationItem.Notification,
        NavigationItem.Profile
    )
    val systemUiController = rememberSystemUiController()
    val pagerState = rememberPagerState(pageCount = { item.size })
    val coroutineScope = rememberCoroutineScope()
    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val bottomSheetState = rememberModalBottomSheetState()
    val context = LocalContext.current

    // 注意：不要在离开 Index 路由时全量清理资源，以免返回后列表被重置
    LaunchedEffect(Unit) {
        systemUiController.setNavigationBarColor(Color.Transparent)
    }
    LaunchedEffect(model.openDrawer) {
        if (model.openDrawer) {
            drawerState.open()
            model.openDrawer = false
        }
    }
    CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
        ModalNavigationDrawer(
            drawerState = drawerState,
            gesturesEnabled = drawerState.isOpen,
            drawerContent = {
                CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) {
                    Column(
                        modifier = Modifier
                            .requiredWidth(250.dp)
                            .fillMaxHeight()
                            .background(
                                AppColors.background
                            )
                    ) {
                        Spacer(modifier = Modifier.height(88.dp))
                        NavItem(
                            iconRes = R.drawable.rave_now_nav_account,
                            label = stringResource(R.string.account_and_security),
                            modifier = Modifier.noRippleClickable {
                                coroutineScope.launch {
                                    drawerState.close()
                                    navController.navigate(NavigationRoute.AccountSetting.route)
                                }

                            }
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        NavItem(
                            iconRes = R.drawable.rider_pro_favourited,
                            label = stringResource(R.string.favourites),
                            modifier = Modifier.noRippleClickable {
                                coroutineScope.launch {
                                    drawerState.close()
                                    navController.navigate(NavigationRoute.FavouriteList.route)
                                }

                            }
                        )

                        NavItem(
                            iconRes = R.drawable.rave_now_nav_night,
                            label = stringResource(R.string.dark_mode),
                            rightContent = {
                                Switch(
                                    checked = AppState.darkMode,
                                    onCheckedChange = {
                                        AppState.switchTheme()
                                    },

                                    colors = SwitchDefaults.colors(
                                        checkedThumbColor = Color.White,
                                        checkedTrackColor = AppColors.main,
                                        uncheckedThumbColor = Color.White,
                                        uncheckedTrackColor = AppColors.main.copy(alpha = 0.5f),
                                        uncheckedBorderColor = Color.Transparent
                                    ),
                                    modifier = Modifier.scale(0.8f)
                                )
                            }
                        )
                        // divider
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 16.dp, bottom = 16.dp, start = 16.dp, end = 16.dp)
                        ) {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(1.dp)
                                    .background(AppColors.divider)
                            )
                        }
                        NavItem(
                            iconRes = R.drawable.rave_now_nav_about,
                            label = stringResource(R.string.blocked),
                            modifier = Modifier.noRippleClickable {
                                coroutineScope.launch {
                                    drawerState.close()
                                    navController.navigate(NavigationRoute.AboutScreen.route)
                                }
                            }
                        )
                        NavItem(
                            iconRes = R.drawable.rave_now_nav_about,
                            label = stringResource(R.string.feedback),
                            modifier = Modifier.noRippleClickable {
                                coroutineScope.launch {
                                    drawerState.close()
                                    navController.navigate(NavigationRoute.AboutScreen.route)
                                }
                            }
                        )
                        NavItem(
                            iconRes = R.drawable.rave_now_nav_about,
                            label = stringResource(R.string.about_rave_now),
                            modifier = Modifier.noRippleClickable {
                                coroutineScope.launch {
                                    drawerState.close()
                                    navController.navigate(NavigationRoute.AboutScreen.route)
                                }
                            }
                        )
                        // divider
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 16.dp, bottom = 16.dp, start = 16.dp, end = 16.dp)
                        ) {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(1.dp)
                                    .background(AppColors.divider)
                            )
                        }

//                        NavItem(
//                            iconRes = R.drawable.rave_now_nav_switch,
//                            label = "Switch Account"
//                        )
//                        Spacer(modifier = Modifier.height(16.dp))
                        NavItem(
                            iconRes = R.drawable.rave_now_nav_logout,
                            label = stringResource(R.string.logout),
                            modifier = Modifier.noRippleClickable {
                                coroutineScope.launch {
                                    drawerState.close()
                                    // 只有非游客用户才需要取消注册推送设备
                                    if (!AppStore.isGuest) {
                                        Messaging.unregisterDevice(context)
                                    }
                                    AppStore.apply {
                                        token = null
                                        rememberMe = false
                                        isGuest = false  // 清除游客状态
                                        saveData()
                                    }
                                    // 删除推送渠道

                                    navController.navigate(NavigationRoute.Login.route) {
                                        popUpTo(NavigationRoute.Login.route) {
                                            inclusive = true
                                        }
                                    }
                                    AppState.ReloadAppState(context)
                                }
                            }
                        )

                    }
                }
            }
        ) {
            CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) {
                Scaffold(
                    bottomBar = {
                        NavigationBar(
                            modifier = Modifier.height(58.dp + navigationBarHeight),
                            containerColor = AppColors.background
                        ) {
                            item.forEachIndexed { idx, it ->
                                val isSelected = model.tabIndex == idx
                                val iconTint by animateColorAsState(
                                    targetValue = if (isSelected) AppColors.brandColorsColor else AppColors.text,
                                    animationSpec = tween(durationMillis = 250), label = ""
                                )

                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .padding(top = 2.dp)
                                        .noRippleClickable {
                                            if (it.route === NavigationItem.Add.route) {
                                                // 检查游客模式，如果是游客则跳转登录
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CREATE_POST)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                    return@noRippleClickable
                                                }
                                                // 显示创建底部弹窗
                                                model.showCreateBottomSheet = true
                                                return@noRippleClickable
                                            }

                                            // 检查消息tab的游客模式
                                            if (it.route === NavigationItem.Notification.route) {
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.VIEW_MESSAGES)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                    return@noRippleClickable
                                                }
                                            }

                                            // 检查我的tab的游客模式
                                            if (it.route === NavigationItem.Profile.route) {
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.VIEW_PROFILE)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                    return@noRippleClickable
                                                }
                                            }

                                            coroutineScope.launch {
                                                pagerState.scrollToPage(idx)
                                            }
                                            model.tabIndex = idx
                                        },
                                    contentAlignment = Alignment.Center
                                ) {
                                    Column(
                                        horizontalAlignment = Alignment.CenterHorizontally,
                                        verticalArrangement = Arrangement.Center
                                    ) {
                                        if (it.route == NavigationItem.Add.route) {
                                            // Add按钮：只显示大图标
                                            Image(
                                                painter = painterResource(if (isSelected) it.selectedIcon() else it.icon()),
                                                contentDescription = it.label(),
                                                modifier = Modifier.size(32.dp),
                                                colorFilter = if (!isSelected) ColorFilter.tint(AppColors.text) else null
                                            )
                                        } else {
                                            // 其他按钮：图标+文字
                                            Box(
                                                modifier = Modifier
                                                    .width(48.dp)
                                                    .height(32.dp)
                                                    .background(
                                                        color = if (isSelected) AppColors.brandColorsColor.copy(alpha = 0.15f) else Color.Transparent,
                                                        shape = RoundedCornerShape(12.dp)
                                                    ),
                                                contentAlignment = Alignment.Center
                                            ) {
                                                Image(
                                                    painter = painterResource(if (isSelected) it.selectedIcon() else it.icon()),
                                                    contentDescription = it.label(),
                                                    modifier = Modifier.size(24.dp),
                                                    colorFilter = if (!isSelected) ColorFilter.tint(AppColors.text) else null
                                                )
                                            }

                                            // 文字标签，可控制间距
                                            Spacer(modifier = Modifier.height(1.dp))

                                            Text(
                                                text = it.label(),
                                                fontSize = 10.sp,
                                                color = if (isSelected) Color.Blue else AppColors.text,
                                                fontWeight = if (isSelected) FontWeight.W600 else FontWeight.Normal
                                            )
                                        }
                                    }
                                }

                            }
                        }
                    }
                ) { innerPadding ->
                    innerPadding
                    HorizontalPager(
                        state = pagerState,
                        modifier = Modifier
                            .background(AppColors.background)
                            .padding(0.dp),
                        beyondBoundsPageCount = 4,
                        userScrollEnabled = false
                    ) { page ->
                        when (page) {
                            0 -> Agent()
                            1 -> Home()
                            2 -> Add()
                            3 -> Notifications()
                            4 -> Profile()
                        }
                    }
                }
            }
        }
        
        // 创建底部弹窗
        if (model.showCreateBottomSheet) {
            CreateBottomSheet(
                sheetState = bottomSheetState,
                onDismiss = {
                    // 使用协程来优雅地关闭弹窗
                    coroutineScope.launch {
                        bottomSheetState.hide()
                        model.showCreateBottomSheet = false
                    }
                },
                onAiClick = {
                    // 使用协程来优雅地关闭弹窗并导航
                    coroutineScope.launch {
                        bottomSheetState.hide() // 触发关闭动画
                        model.showCreateBottomSheet = false
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CREATE_AGENT)) {
                            navController.navigate(NavigationRoute.Login.route)
                        } else {
                            navController.navigate(NavigationRoute.AddAgent.route)
                        }
                    }
                },
                onGroupChatClick = {
                    // 使用协程来优雅地关闭弹窗并导航
                    coroutineScope.launch {
                        bottomSheetState.hide() // 触发关闭动画
                        model.showCreateBottomSheet = false
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.JOIN_GROUP_CHAT)) {
                            navController.navigate(NavigationRoute.Login.route)
                        } else {
                            navController.navigate(NavigationRoute.CreateGroupChat.route)
                        }
                    }
                },
                onMomentClick = {
                    // 使用协程来优雅地关闭弹窗并导航
                    coroutineScope.launch {
                        bottomSheetState.hide() // 触发关闭动画
                        model.showCreateBottomSheet = false
                        // 导航到动态创建页面
                        NewPostViewModel.asNewPost()
                        navController.navigate(NavigationRoute.NewPost.route)
                    }
                }
            )
        }
    }

}

@Composable
fun Home() {
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current

    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Transparent, darkIcons = !AppState.darkMode)
    }

    // 注意：避免在离开 Home 时清理动态资源，防止返回详情后触发重新加载

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        MomentsList()
    }
}


@Composable
fun Street() {
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current

    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Transparent, darkIcons = !AppState.darkMode)
    }

    // 页面退出时清理搜索相关资源
    DisposableEffect(Unit) {
        onDispose {
            ResourceCleanupManager.cleanupPageResources("search")
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        StreetPage()
    }
}

@Composable
fun Add() {
    val systemUiController = rememberSystemUiController()
    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Black, darkIcons = !AppState.darkMode)
    }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        AddPage()
    }
}

@Composable
fun Video() {
    val systemUiController = rememberSystemUiController()
    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Black, darkIcons = false)
    }
    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        ShortVideo()
    }
}


@Composable
fun Profile() {
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current

    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Transparent, !AppState.darkMode)
    }

    // 页面退出时清理个人资料相关资源
    DisposableEffect(Unit) {
        onDispose {
            ResourceCleanupManager.cleanupPageResources("profile")
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        ProfileWrap()
    }
}

@Composable
fun Notifications() {
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current

    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Transparent, !AppState.darkMode)
    }

    // 页面退出时清理消息相关资源
    DisposableEffect(Unit) {
        onDispose {
            ResourceCleanupManager.cleanupPageResources("message")
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        NotificationsScreen()
    }
}

@Composable
fun NavItem(
    iconRes: Int,
    label: String,
    modifier: Modifier = Modifier,
    rightContent: @Composable (() -> Unit)? = null
) {
    val appColors = LocalAppTheme.current
    Row(
        modifier = modifier
            .fillMaxWidth()
            .padding(top = 8.dp, start = 16.dp, end = 16.dp, bottom = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Image(
            painter = painterResource(id = iconRes),
            contentDescription = null,
            modifier = Modifier.size(24.dp),
            colorFilter = ColorFilter.tint(appColors.text)
        )
        Text(
            text = label,
            modifier = Modifier
                .padding(start = 8.dp)
                .weight(1f),
            color = appColors.text,
        )
        if (rightContent != null) {
            rightContent()
        } else {
            Image(
                painter = painterResource(id = R.drawable.rave_now_nav_right),
                contentDescription = null,
                modifier = Modifier.size(24.dp),
                colorFilter = ColorFilter.tint(appColors.secondaryText)
            )
        }

    }
}