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

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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
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.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.lifecycle.viewModelScope
import com.aiosman.riderpro.LocalNavController
import com.aiosman.riderpro.R
import com.aiosman.riderpro.ui.NavigationRoute
import com.aiosman.riderpro.ui.composables.CustomAsyncImage
import com.aiosman.riderpro.ui.composables.StatusBarSpacer
import com.aiosman.riderpro.ui.follower.FollowerNoticeViewModel
import com.aiosman.riderpro.ui.like.LikeNoticeViewModel
import com.aiosman.riderpro.ui.modifiers.noRippleClickable
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.launch


/**
 * 消息列表界面
 */
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun NotificationsScreen() {
    val navController = LocalNavController.current
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current
    val state = rememberPullRefreshState(MessageListViewModel.isLoading, onRefresh = {
        MessageListViewModel.viewModelScope.launch {
            MessageListViewModel.initData(context, force = true)
        }
    })
    LaunchedEffect(Unit) {
        systemUiController.setNavigationBarColor(Color.Transparent)
    }
    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        StatusBarSpacer()
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .pullRefresh(state)
        ) {
            Column(
                modifier = Modifier.fillMaxSize(),
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp),
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    NotificationIndicator(
                        MessageListViewModel.likeNoticeCount,
                        R.drawable.rider_pro_moment_like,
                        stringResource(R.string.like_upper)
                    ) {
                        if (MessageListViewModel.likeNoticeCount > 0) {
                            // 刷新点赞消息列表
                            LikeNoticeViewModel.isFirstLoad = true
                            // 清除点赞消息数量
                            MessageListViewModel.clearLikeNoticeCount()
                        }
                        navController.navigate(NavigationRoute.Likes.route)
                    }
                    NotificationIndicator(
                        MessageListViewModel.followNoticeCount,
                        R.drawable.rider_pro_followers,
                        stringResource(R.string.followers_upper)
                    ) {
                        if (MessageListViewModel.followNoticeCount > 0) {
                            // 刷新关注消息列表
                            FollowerNoticeViewModel.isFirstLoad = true
                            MessageListViewModel.clearFollowNoticeCount()
                        }
                        navController.navigate(NavigationRoute.Followers.route)
                    }
//                    NotificationIndicator(
//                        MessageListViewModel.favouriteNoticeCount,
//                        R.drawable.rider_pro_favoriate,
//                        stringResource(R.string.favourites_upper)
//                    ) {
//                        if (MessageListViewModel.favouriteNoticeCount > 0) {
//                            // 刷新收藏消息列表
//                            FavouriteNoticeViewModel.isFirstLoad = true
//                            MessageListViewModel.clearFavouriteNoticeCount()
//                        }
//                        navController.navigate(NavigationRoute.FavouritesScreen.route)
//                    }
                    NotificationIndicator(
                        MessageListViewModel.commentNoticeCount,
                        R.drawable.rider_pro_comment,
                        stringResource(R.string.comment).uppercase()
                    ) {
                        navController.navigate(NavigationRoute.CommentNoticeScreen.route)
                    }
                }
                HorizontalDivider(color = Color(0xFFEbEbEb), modifier = Modifier.padding(16.dp))
                NotificationCounterItem(MessageListViewModel.unReadConversationCount.toInt())
                Box(
                    modifier = Modifier
                        .weight(1f)
                        .fillMaxWidth()
                ) {
                    ChatMessageList(
                        MessageListViewModel.chatList,
                        onUserAvatarClick = { conv ->
                            MessageListViewModel.goToUserDetail(conv, navController)
                        },
                    ) { conv ->
                        MessageListViewModel.goToChat(conv, navController)
                    }
                }
            }
            PullRefreshIndicator(
                MessageListViewModel.isLoading,
                state,
                Modifier.align(Alignment.TopCenter)
            )
        }

    }
}

@Composable
fun NotificationIndicator(
    notificationCount: Int,
    iconRes: Int,
    label: String,
    onClick: () -> Unit
) {
    Box(
        modifier = Modifier
    ) {
        Box(
            modifier = Modifier
                .padding(16.dp)
                .align(Alignment.TopCenter)
                .noRippleClickable {
                    onClick()
                }
        ) {
            if (notificationCount > 0) {
                Box(
                    modifier = Modifier
                        .background(Color(0xFFE53935), RoundedCornerShape(16.dp))
                        .padding(4.dp)
                        .align(Alignment.TopEnd)
                ) {
                    Text(
                        text = notificationCount.toString(),
                        color = Color.White,
                        fontSize = 10.sp,
                        fontWeight = FontWeight.Bold,
                        modifier = Modifier.align(Alignment.Center)
                    )
                }
            }
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
            ) {
                Box(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Image(
                        painter = painterResource(id = iconRes),
                        contentDescription = label,
                        modifier = Modifier.size(24.dp)
                    )
                }
                Box(
                    modifier = Modifier
                ) {
                    Text(label, modifier = Modifier.align(Alignment.Center))
                }

            }
        }
    }

}

@Composable
fun NotificationCounterItem(count: Int) {
    Row(
        modifier = Modifier.padding(vertical = 16.dp, horizontal = 32.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Box(

        ) {
            Image(
                painter = painterResource(id = R.drawable.rider_pro_notification),
                contentDescription = "",
                modifier = Modifier
                    .size(24.dp)

            )

        }
        Spacer(modifier = Modifier.width(24.dp))
        Text(stringResource(R.string.notifications_upper), fontSize = 18.sp)
        Spacer(modifier = Modifier.weight(1f))
        if (count > 0) {
            Box(
                modifier = Modifier
                    .background(Color(0xFFE53935), RoundedCornerShape(16.dp))
                    .padding(horizontal = 8.dp, vertical = 2.dp)
            ) {
                Text(
                    text = count.toString(),
                    color = Color.White,
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                )
            }
        }
    }
}


@Composable
fun ChatMessageList(
    items: List<Conversation>,
    onUserAvatarClick: (Conversation) -> Unit = {},
    onChatClick: (Conversation) -> Unit = {}
) {
    LazyColumn(
        modifier = Modifier.fillMaxSize()
    ) {
        items(items.size) { index ->
            val item = items[index]
            Row(
                modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)
            ) {
                Box {
                    CustomAsyncImage(
                        context = LocalContext.current,
                        imageUrl = item.avatar,
                        contentDescription = item.nickname,
                        modifier = Modifier
                            .size(48.dp)
                            .clip(RoundedCornerShape(48.dp))
                            .noRippleClickable {
                                onUserAvatarClick(item)
                            }
                    )
                }
                Column(
                    modifier = Modifier
                        .weight(1f)
                        .padding(start = 12.dp)
                        .noRippleClickable {
                            onChatClick(item)
                        }
                ) {
                    Row {
                        Text(
                            text = item.nickname,
                            fontSize = 16.sp,
                            modifier = Modifier,
                            fontWeight = FontWeight.Bold
                        )
                        Spacer(modifier = Modifier.weight(1f))
                        Text(
                            text = item.lastMessageTime,
                            fontSize = 14.sp,
                            color = Color(0x66000000)
                        )
                    }
                    Spacer(modifier = Modifier.height(6.dp))
                    Row {
                        Text(
                            text = "${if (item.isSelf) "Me: " else ""}${item.displayText}",
                            fontSize = 14.sp,
                            maxLines = 1,
                            color = Color(0x99000000),
                            modifier = Modifier.weight(1f),
                            overflow = TextOverflow.Ellipsis
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        if (item.unreadCount > 0) {
                            Box(
                                modifier = Modifier
                                    .background(Color(0xFFE53935), CircleShape)
                                    .padding(horizontal = 8.dp, vertical = 2.dp)
                            ) {
                                Text(
                                    text = item.unreadCount.toString(),
                                    color = Color.White,
                                    fontSize = 12.sp,
                                    fontWeight = FontWeight.Bold,
                                    modifier = Modifier.align(Alignment.Center)
                                )
                            }
                            Spacer(modifier = Modifier.width(8.dp))
                        }
                    }
                }
            }
        }
    }
}