package com.aiosman.ravenow.ui.index.tabs.message

import android.widget.Toast
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.asPaddingValues
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.offset

import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.unit.offset
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.composables.TabItem
import com.aiosman.ravenow.ui.composables.TabSpacer
import com.aiosman.ravenow.ui.composables.rememberDebouncedNavigation
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.follower.FollowerNoticeViewModel
import com.aiosman.ravenow.ui.index.tabs.message.tab.AgentChatListScreen
import com.aiosman.ravenow.ui.index.tabs.message.tab.AgentChatListViewModel
import com.aiosman.ravenow.ui.index.tabs.message.tab.FriendChatListScreen
import com.aiosman.ravenow.ui.index.tabs.message.tab.FriendChatListViewModel
import com.aiosman.ravenow.ui.index.tabs.message.tab.GroupChatListScreen
import com.aiosman.ravenow.ui.index.tabs.message.tab.GroupChatListViewModel
import com.aiosman.ravenow.ui.like.LikeNoticeViewModel
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.launch


/**
 * 消息列表界面
 */
@OptIn(ExperimentalMaterialApi::class, ExperimentalFoundationApi::class)
@Composable
fun NotificationsScreen() {
    val debouncer = rememberDebouncer()
    // 计算总未读消息数
    val totalUnreadCount = AgentChatListViewModel.totalUnreadCount + 
                          GroupChatListViewModel.totalUnreadCount + 
                          FriendChatListViewModel.totalUnreadCount
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current
    var pagerState = rememberPagerState (pageCount = { 3 })
    var scope = rememberCoroutineScope()
    val state = rememberPullRefreshState(MessageListViewModel.isLoading, onRefresh = {
        MessageListViewModel.viewModelScope.launch {
            MessageListViewModel.initData(context, force = true, loadChat = AppState.enableChat)
        }
        // 刷新群聊列表以更新未读消息数
        GroupChatListViewModel.refreshPager(context = context)
        // 刷新智能体列表以更新未读消息数
        AgentChatListViewModel.refreshPager(context = context)
        // 刷新朋友列表以更新未读消息数
        FriendChatListViewModel.refreshPager(context = context)
    })
    val navigationBarPaddings =
        WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + 48.dp
    val statusBarPaddingValues = WindowInsets.systemBars.asPaddingValues()
    LaunchedEffect(Unit) {
        systemUiController.setNavigationBarColor(Color.Transparent)
        MessageListViewModel.initData(context, loadChat = AppState.enableChat)
        // 初始化群聊列表以获取未读消息数
        GroupChatListViewModel.refreshPager(context = context)
        // 初始化智能体列表以获取未读消息数
        AgentChatListViewModel.refreshPager(context = context)
        // 初始化朋友列表以获取未读消息数
        FriendChatListViewModel.refreshPager(context = context)
    }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(
                bottom = navigationBarPaddings,

            ),
    ) {
        StatusBarSpacer()
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .pullRefresh(state)
        ) {

            Column(
                modifier = Modifier.fillMaxSize(),
            ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(44.dp)
                            .padding(horizontal = 16.dp),
                        horizontalArrangement = Arrangement.Start,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = stringResource(R.string.main_message),
                            fontSize = 20.sp,
                            fontWeight = FontWeight.W900,
                            color = AppColors.text
                        )

                        Spacer(modifier = Modifier.weight(1f))

                        Image(
                            painter = painterResource(id = R.drawable.rider_pro_nav_search),
                            contentDescription = "search",
                            modifier = Modifier
                                .size(24.dp)
                                .noRippleClickable {
                                    // TODO: 实现搜索功能
                                },
                            colorFilter = ColorFilter.tint(AppColors.text)
                        )

                        Spacer(modifier = Modifier.width(16.dp))

                        Box {
                            Image(
                                painter = painterResource(id = R.drawable.rider_pro_notification),
                                contentDescription = "notifications",
                                modifier = Modifier
                                    .size(24.dp)
                                    .noRippleClickable {
                                        // TODO: 实现通知功能
                                    },
                                colorFilter = ColorFilter.tint(AppColors.text)
                            )

                            // 通知红点
                            val totalNoticeCount = MessageListViewModel.likeNoticeCount +
                                    MessageListViewModel.followNoticeCount +
                                    MessageListViewModel.commentNoticeCount +
                                    MessageListViewModel.favouriteNoticeCount

                            if (totalNoticeCount > 0) {
                                Box(
                                    modifier = Modifier
                                        .size(8.dp)
                                        .background(
                                            color = Color(0xFFFF3B30),
                                            shape = CircleShape
                                        )
                                        .align(Alignment.TopEnd)
                                        .offset(x = 8.dp, y = (-4).dp)
                                )
                            }
                        }
                    }

                //创建群聊//
//                    Image(
//                        painter = painterResource(id = R.drawable.rider_pro_group),
//                        contentDescription = "add",
//                        modifier = Modifier
//                            .size(24.dp)
//                            .noRippleClickable {
//                                debouncer {
//                                    navController.navigate(NavigationRoute.CreateGroupChat.route)
//                                }
//                            },
//                        colorFilter = ColorFilter.tint(AppColors.text)
//                    )


//                // 搜索栏//
//                Box(
//                    modifier = Modifier
//                        .fillMaxWidth()
//                        .padding(horizontal = 16.dp, vertical = 8.dp)
//                        .height(40.dp)
//
//                        .noRippleClickable {
//                        },
//                    contentAlignment = Alignment.CenterStart
//                )
//                {
//                    Row(
//                        modifier = Modifier
//                            .height(36.dp)
//                            .fillMaxWidth()
//                            .clip(shape = RoundedCornerShape(8.dp))
//                            .background(AppColors.inputBackground)
//                            .padding(horizontal = 8.dp, vertical = 0.dp)
//                            .noRippleClickable {
//                                // 搜索框点击事件
//                            },
//                        verticalAlignment = Alignment.CenterVertically
//                    ) {
//                        Icon(
//                            painter = painterResource(id = R.drawable.rider_pro_nav_search),
//                            contentDescription = null,
//                            tint = AppColors.inputHint
//                        )
//                        Box {
//                            androidx.compose.material.Text(
//                                text = stringResource(R.string.search),
//                                modifier = Modifier.padding(start = 8.dp),
//                                color = AppColors.inputHint,
//                                fontSize = 17.sp
//                            )
//                        }
//                    }
//                }

                //赞、粉丝、评论//
//                Row(
//                    modifier = Modifier
//                        .fillMaxWidth()
//                        .padding(horizontal = 16.dp),
//                    horizontalArrangement = Arrangement.SpaceBetween,
//                ) {
//                    val likeDebouncer = rememberDebouncer()
//                    val followDebouncer = rememberDebouncer()
//                    val commentDebouncer = rememberDebouncer()
//
//                    NotificationIndicator(
//                        MessageListViewModel.likeNoticeCount,
//                        R.mipmap.rider_pro_like,
//                        stringResource(R.string.like_upper),
//                        Color(0xFFFAFD5D)
//                    ) {
//                        likeDebouncer {
//                            if (MessageListViewModel.likeNoticeCount > 0) {
//                                // 刷新点赞消息列表
//                                LikeNoticeViewModel.isFirstLoad = true
//                                // 清除点赞消息数量
//                                MessageListViewModel.clearLikeNoticeCount()
//                            }
//                            navController.navigate(NavigationRoute.Likes.route)
//                        }
//                    }
//                    NotificationIndicator(
//                        MessageListViewModel.followNoticeCount,
//                        R.mipmap.rider_pro_followers,
//                        stringResource(R.string.followers_upper),
//                        Color(0xFFF470FE)
//                    ) {
//                        followDebouncer {
//                            if (MessageListViewModel.followNoticeCount > 0) {
//                                // 刷新关注消息列表
//                                FollowerNoticeViewModel.isFirstLoad = true
//                                MessageListViewModel.clearFollowNoticeCount()
//                            }
//                            navController.navigate(NavigationRoute.Followers.route)
//                        }
//                    }
//                    NotificationIndicator(
//                        MessageListViewModel.commentNoticeCount,
//                        R.mipmap.rider_pro_comment,
//                        stringResource(R.string.comment).uppercase(),
//                        Color(0xFF6246FF)
//                    ) {
//                        commentDebouncer {
//                            navController.navigate(NavigationRoute.CommentNoticeScreen.route)
//                        }
//                    }
//                }
                Spacer(modifier = Modifier.height(23.dp))
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentHeight()
                        .padding(start = 16.dp,bottom = 16.dp),
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.Bottom
                ) {
                    val tabDebouncer = rememberDebouncer()

                    Box {
                        TabItem(
                            text = stringResource(R.string.chat_ai),
                            isSelected = pagerState.currentPage == 0,
                            onClick = {
                                tabDebouncer {
                                    scope.launch {
                                        pagerState.animateScrollToPage(0)
                                    }
                                }
                            }
                        )

                        // 智能体未读消息红点
                        if (AgentChatListViewModel.totalUnreadCount > 0) {
                            Box(
                                modifier = Modifier
                                    .size(8.dp)
                                    .background(
                                        color = Color(0xFFFF3B30),
                                        shape = CircleShape
                                    )
                                    .align(Alignment.TopEnd)
                                    .offset(x = 8.dp, y = (-4).dp)
                            )
                        }
                    }
                    TabSpacer()
                    Box {
                        TabItem(
                            text = stringResource(R.string.chat_group),
                            isSelected = pagerState.currentPage == 1,
                            onClick = {
                                tabDebouncer {
                                    scope.launch {
                                        pagerState.animateScrollToPage(1)
                                    }
                                }
                            }
                        )

                        // 群聊未读消息红点
                        if (GroupChatListViewModel.totalUnreadCount > 0) {
                            Box(
                                modifier = Modifier
                                    .size(8.dp)
                                    .background(
                                        color = Color(0xFFFF3B30),
                                        shape = CircleShape
                                    )
                                    .align(Alignment.TopEnd)
                                    .offset(x = 8.dp, y = (-4).dp)
                            )
                        }
                    }
                    TabSpacer()
                    Box {
                        TabItem(
                            text = stringResource(R.string.chat_friend),
                            isSelected = pagerState.currentPage == 2,
                            onClick = {
                                tabDebouncer {
                                    scope.launch {
                                        pagerState.animateScrollToPage(2)
                                    }
                                }
                            }
                        )

                        // 朋友未读消息红点
                        if (FriendChatListViewModel.totalUnreadCount > 0) {
                            Box(
                                modifier = Modifier
                                    .size(8.dp)
                                    .background(
                                        color = Color(0xFFFF3B30),
                                        shape = CircleShape
                                    )
                                    .align(Alignment.TopEnd)
                                    .offset(x = 8.dp, y = (-4).dp)
                            )
                        }
                    }
                }
                HorizontalPager(
                    state = pagerState,
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f)
                ) {
                    when (it) {
                        0 -> {
                            AgentChatListScreen()
                        }

                        1 -> {
                            GroupChatListScreen()
                        }

                        2 -> {
                            FriendChatListScreen()
                        }
                    }
                }

            }
        }

    }
}

@Composable
fun NotificationIndicator(
    notificationCount: Int,
    iconRes: Int,
    label: String,
    backgroundColor: Color = Color.Transparent,
    onClick: () -> Unit
) {
    val AppColors = LocalAppTheme.current

    Box(
        modifier = Modifier
    ) {
        Box(
            modifier = Modifier
                .padding(16.dp)
                .align(Alignment.TopCenter)
                .noRippleClickable {
                    onClick()
                }
        ) {

            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Box(
                    modifier = Modifier
                        .size(69.dp)
                        .padding(5.dp)
                        .background(color = backgroundColor,
                            shape = RoundedCornerShape(16.dp)),
                    contentAlignment = Alignment.Center
                ) {
                    Image(
                        painter = painterResource(id = iconRes),
                        contentDescription = label,
                        modifier = Modifier.size(24.dp)
                    )
                }
                Box(
                    modifier = Modifier
                ) {
                    Text(label, modifier = Modifier.align(Alignment.Center).padding(top = 8.dp), color = AppColors.text)
                }

            }
            if (notificationCount > 0) {
                Box(
                    modifier = Modifier
                        .background(AppColors.main, RoundedCornerShape(16.dp))
                        .padding(horizontal = 8.dp, vertical = 4.dp)
                        .align(Alignment.TopEnd)
                ) {
                    Text(
                        text = if (notificationCount > 99) "99+" else notificationCount.toString(),
                        color = AppColors.mainText,
                        fontSize = 10.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.align(Alignment.Center)
                    )
                }
            }
        }
    }

}



