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

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
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.CircularProgressIndicator
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 com.aiosman.ravenow.AppState
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.network.NetworkErrorContentCompact
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.utils.NetworkUtils
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.graphics.Brush
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.foundation.layout.PaddingValues

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun FriendChatListScreen() {
    val context = LocalContext.current
    val navController = LocalNavController.current
    val AppColors = LocalAppTheme.current
    val model = FriendChatListViewModel

    val state = rememberPullRefreshState(
        refreshing = FriendChatListViewModel.refreshing,
        onRefresh = {
            FriendChatListViewModel.refreshPager(pullRefresh = true, context = context)
        }
    )

    LaunchedEffect(Unit) {
        FriendChatListViewModel.refreshPager(context = context)
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .pullRefresh(state)
        ) {
            if (FriendChatListViewModel.friendChatList.isEmpty() && !FriendChatListViewModel.isLoading) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(horizontal = 16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier.offset(y = (-40).dp)
                    ) {
                        val isNetworkAvailable = NetworkUtils.isNetworkAvailable(context)

                        if (isNetworkAvailable) {
                            Image(
                                painter = painterResource(id = R.mipmap.invalid_name_3),
                                contentDescription = "null data",
                                modifier = Modifier.size(120.dp)
                            )
                            Spacer(modifier = Modifier.height(12.dp))
                            Text(
                                text = stringResource(R.string.no_one_knocked_yet),
                                color = AppColors.text,
                                fontSize = 16.sp,
                                fontWeight = FontWeight.W600,
                                textAlign = TextAlign.Center,
                                modifier = Modifier.padding(horizontal = 24.dp),
                                maxLines = 2,
                                overflow = TextOverflow.Ellipsis
                            )
                        } else {
                            NetworkErrorContentCompact(
                                onReload = {
                                    FriendChatListViewModel.refreshPager(pullRefresh = true, context = context)
                                }
                            )
                        }
                    }
                }
            } else {
                LazyColumn(
                    modifier = Modifier.fillMaxSize()
                ) {
                    itemsIndexed(
                        items = FriendChatListViewModel.friendChatList,
                        key = { _, item -> item.id }
                    ) { index, item ->
                        FriendChatItem(
                            conversation = item,
                            onUserAvatarClick = { conv ->
                                FriendChatListViewModel.goToUserDetail(conv, navController)
                            },
                            onChatClick = { conv ->
                                if (NetworkUtils.isNetworkAvailable(context)) {
                                    FriendChatListViewModel.goToChat(conv, navController)
                                } else {
                                    android.widget.Toast.makeText(context, "网络连接异常，请检查网络设置", android.widget.Toast.LENGTH_SHORT).show()
                                }
                            }
                        )

                    }

                    if (FriendChatListViewModel.isLoading && FriendChatListViewModel.friendChatList.isNotEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    color = AppColors.main
                                )
                            }
                        }
                    }
                }
            }

            PullRefreshIndicator(
                refreshing = FriendChatListViewModel.refreshing,
                state = state,
                modifier = Modifier.align(Alignment.TopCenter)
            )
        }

        FriendChatListViewModel.error?.let { error ->
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = error,
                    color = AppColors.error,
                    fontSize = 14.sp
                )
            }
        }
    }
}

@Composable
fun FriendChatItem(
    conversation: FriendConversation,
    onUserAvatarClick: (FriendConversation) -> Unit = {},
    onChatClick: (FriendConversation) -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val chatDebouncer = rememberDebouncer()
    val avatarDebouncer = rememberDebouncer()

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 12.dp)
            .noRippleClickable {
                chatDebouncer {
                    onChatClick(conversation)
                }
            },
        verticalAlignment = Alignment.CenterVertically
    ) {
        Box {
            CustomAsyncImage(
                context = LocalContext.current,
                imageUrl = conversation.avatar,
                contentDescription = conversation.trtcUserId,
                modifier = Modifier
                    .size(48.dp)
                    .clip(RoundedCornerShape(48.dp))
                    .noRippleClickable {
                        avatarDebouncer {
                            onUserAvatarClick(conversation)
                        }
                    }
            )
        }

        Column(
            modifier = Modifier
                .weight(1f)
                .padding(start = 12.dp, top = 2.dp),
            verticalArrangement = Arrangement.Center
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = conversation.nickname,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Bold,
                    color = AppColors.text,
                    modifier = Modifier.weight(1f)
                )

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

                Text(
                    text = conversation.lastMessageTime,
                    fontSize = 11.sp,
                    color = AppColors.secondaryText
                )
            }

            Spacer(modifier = Modifier.height(6.dp))

            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "${if (conversation.isSelf) stringResource(R.string.friend_chat_me_prefix) else ""}${conversation.displayText}",
                    fontSize = 12.sp,
                    color = AppColors.secondaryText,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.weight(1f)
                )

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

                if (conversation.unreadCount > 0) {
                    Box(
                        modifier = Modifier
                            .size(if (conversation.unreadCount > 99) 24.dp else 20.dp)
                            .background(
                                color = Color(0xFFFF3B30),
                                shape = CircleShape
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = if (conversation.unreadCount > 99) "99+" else conversation.unreadCount.toString(),
                            color = Color.White,
                            fontSize = if (conversation.unreadCount > 99) 11.sp else 12.sp,
                            fontWeight = FontWeight.Bold
                        )
                    }
                }
            }
        }
    }
}

