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

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.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.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
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.res.stringResource
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.NavigationRoute
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.utils.NetworkUtils

/**
 * 智能体聊天列表页面
 */
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun AgentChatListScreen() {
    val context = LocalContext.current
    val navController = LocalNavController.current
    val AppColors = LocalAppTheme.current
    val model = AgentChatListViewModel
    
    val state = rememberPullRefreshState(
        refreshing = AgentChatListViewModel.refreshing,
        onRefresh = {
            AgentChatListViewModel.refreshPager(pullRefresh = true, context = context)
        }
    )

    // 初始化数据
    LaunchedEffect(Unit) {
        AgentChatListViewModel.refreshPager(context = context)
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        // 聊天列表
        Box(
            modifier = Modifier
                .fillMaxSize()
                .pullRefresh(state)
        ) {
            if (AgentChatListViewModel.agentChatList.isEmpty() && !AgentChatListViewModel.isLoading) {
                // 空状态
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,

                ) {
                    Spacer(modifier = Modifier.height(39.dp))
                    Image(
                        painter = painterResource(
                            id = if(AppState.darkMode) R.mipmap.qs_znt_qs_as_img
                            else R.mipmap.qs_znt_qs_img),
                        contentDescription = "null data",
                        modifier = Modifier
                            .size(181.dp)
                    )
                    Spacer(modifier = Modifier.height(24.dp))
                    Text(
                        text = stringResource(R.string.agent_chat_empty_title),
                        color = AppColors.text,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.W600
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = stringResource(R.string.agent_chat_empty_subtitle),
                        color = AppColors.secondaryText,
                        fontSize = 14.sp
                    )
                }
            } else {
                LazyColumn(
                    modifier = Modifier.fillMaxSize()
                ) {
                    itemsIndexed(
                        items = AgentChatListViewModel.agentChatList,
                        key = { _, item -> item.id }
                    ) { index, item ->
                        AgentChatItem(
                            conversation = item,
                            onUserAvatarClick = { conv ->
                                AgentChatListViewModel.goToUserDetail(conv, navController)
                            },
                            onChatClick = { conv ->
                                if (NetworkUtils.isNetworkAvailable(context)) {
                                    model.createSingleChat(conv.trtcUserId)
                                    model.goToChatAi(conv.trtcUserId,navController)
                                } else {
                                    android.widget.Toast.makeText(context, "网络连接异常，请检查网络设置", android.widget.Toast.LENGTH_SHORT).show()
                                }
                            }
                        )

                    }
                    
                    // 加载更多指示器
                    if (AgentChatListViewModel.isLoading && AgentChatListViewModel.agentChatList.isNotEmpty()) {
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(16.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    color = AppColors.main
                                )
                            }
                        }
                    }
                }
            }
            
            // 下拉刷新指示器
            PullRefreshIndicator(
                refreshing = AgentChatListViewModel.refreshing,
                state = state,
                modifier = Modifier.align(Alignment.TopCenter)
            )
        }
        
        // 错误信息显示
        AgentChatListViewModel.error?.let { error ->
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = error,
                    color = AppColors.error,
                    fontSize = 14.sp
                )
            }
        }
    }
}

@Composable
fun AgentChatItem(
    conversation: AgentConversation,
    onUserAvatarClick: (AgentConversation) -> Unit = {},
    onChatClick: (AgentConversation) -> 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.nickname,
                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
                        )
                    }
                }
            }
        }
    }
}
