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

import android.widget.Toast
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.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.Brush
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.TextAlign
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.modifiers.noRippleClickable
import com.aiosman.ravenow.utils.NetworkUtils
import com.aiosman.ravenow.ui.network.NetworkErrorContentCompact
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.ui.text.font.FontFamily

data class CombinedConversation(
    val type: String, // "agent", "group", or "friend"
    val agentConversation: AgentConversation? = null,
    val groupConversation: GroupConversation? = null,
    val friendConversation: FriendConversation? = null
) {
    val id: String
        get() = when (type) {
            "agent" -> "agent_${agentConversation?.id ?: 0}"
            "group" -> "group_${groupConversation?.id ?: 0}"
            "friend" -> "friend_${friendConversation?.id ?: 0}"
            else -> ""
        }

    val avatar: String
        get() = when (type) {
            "agent" -> agentConversation?.avatar ?: ""
            "group" -> groupConversation?.avatar ?: ""
            "friend" -> friendConversation?.avatar ?: ""
            else -> ""
        }

    val name: String
        get() = when (type) {
            "agent" -> agentConversation?.nickname ?: ""
            "group" -> groupConversation?.groupName ?: ""
            "friend" -> friendConversation?.nickname ?: ""
            else -> ""
        }

    val lastMessageTime: String
        get() = when (type) {
            "agent" -> agentConversation?.lastMessageTime ?: ""
            "group" -> groupConversation?.lastMessageTime ?: ""
            "friend" -> friendConversation?.lastMessageTime ?: ""
            else -> ""
        }

    val displayText: String
        get() = when (type) {
            "agent" -> agentConversation?.displayText ?: ""
            "group" -> groupConversation?.displayText ?: ""
            "friend" -> friendConversation?.displayText ?: ""
            else -> ""
        }

    val unreadCount: Int
        get() = when (type) {
            "agent" -> agentConversation?.unreadCount ?: 0
            "group" -> groupConversation?.unreadCount ?: 0
            "friend" -> friendConversation?.unreadCount ?: 0
            else -> 0
        }

    val isSelf: Boolean
        get() = when (type) {
            "agent" -> agentConversation?.isSelf ?: false
            "group" -> groupConversation?.isSelf ?: false
            "friend" -> friendConversation?.isSelf ?: false
            else -> false
        }
}

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

    var allConversations by remember { mutableStateOf<List<CombinedConversation>>(emptyList()) }
    var refreshing by remember { mutableStateOf(false) }
    var isLoading by remember { mutableStateOf(false) }
    var error by remember { mutableStateOf<String?>(null) }

    // 监听各个 ViewModel 的列表变化
    val agentChatList = AgentChatListViewModel.agentChatList
    val groupChatList = GroupChatListViewModel.groupChatList
    val friendChatList = FriendChatListViewModel.friendChatList

    // 当列表变化时，自动更新合并列表
    LaunchedEffect(agentChatList, groupChatList, friendChatList) {
        val combinedList = mutableListOf<CombinedConversation>()

        agentChatList.forEach { agent ->
            combinedList.add(CombinedConversation(type = "agent", agentConversation = agent))
        }

        groupChatList.forEach { group ->
            combinedList.add(CombinedConversation(type = "group", groupConversation = group))
        }

        friendChatList.forEach { friend ->
            val isDuplicate = combinedList.any {
                it.type == "agent" && it.agentConversation?.trtcUserId == friend.trtcUserId
            }

            if (!isDuplicate) {
                combinedList.add(CombinedConversation(type = "friend", friendConversation = friend))
            }
        }

        // 按最后消息时间排序
        val sortedList = combinedList.sortedByDescending {
            it.lastMessageTime
        }

        allConversations = sortedList
    }

    // 监听加载状态
    val isAnyLoading = AgentChatListViewModel.isLoading || 
                       GroupChatListViewModel.isLoading || 
                       FriendChatListViewModel.isLoading

    // 当加载状态变化时，更新 isLoading
    LaunchedEffect(isAnyLoading) {
        if (isAnyLoading) {
            // 如果有任何数据正在加载，确保显示加载状态
            if (!isLoading) {
                isLoading = true
            }
        } else {
            // 所有数据加载完成
            if (isLoading) {
                isLoading = false
            }
        }
    }

    val state = rememberPullRefreshState(
        refreshing = refreshing,
        onRefresh = {
            refreshing = true
            // 刷新所有类型的数据
            AgentChatListViewModel.refreshPager(pullRefresh = true, context = context)
            GroupChatListViewModel.refreshPager(pullRefresh = true, context = context)
            FriendChatListViewModel.refreshPager(pullRefresh = true, context = context)
        }
    )

    // 监听刷新状态
    LaunchedEffect(AgentChatListViewModel.refreshing, GroupChatListViewModel.refreshing, FriendChatListViewModel.refreshing) {
        val isAnyRefreshing = AgentChatListViewModel.refreshing || 
                              GroupChatListViewModel.refreshing || 
                              FriendChatListViewModel.refreshing
        if (!isAnyRefreshing && refreshing) {
            refreshing = false
        }
    }

    LaunchedEffect(Unit) {
        isLoading = true
        // 初始化加载所有类型的数据
        AgentChatListViewModel.refreshPager(context = context)
        GroupChatListViewModel.refreshPager(context = context)
        FriendChatListViewModel.refreshPager(context = context)
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .pullRefresh(state)
        ) {
            if (allConversations.isEmpty() && !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 = {
                                    isLoading = true
                                    // 重新加载所有类型的数据
                                    AgentChatListViewModel.refreshPager(context = context)
                                    GroupChatListViewModel.refreshPager(context = context)
                                    FriendChatListViewModel.refreshPager(context = context)
                                }
                            )
                        }
                    }
                }
            } else {
                LazyColumn(
                    modifier = Modifier.fillMaxSize()
                ) {
                    itemsIndexed(
                        items = allConversations,
                        key = { _, item -> item.id }
                    ) { index, item ->
                        when (item.type) {
                            "agent" -> {
                                item.agentConversation?.let { agent ->
                                    AgentChatItem(
                                        conversation = agent,
                                        onUserAvatarClick = { conv ->
                                            AgentChatListViewModel.goToUserDetail(conv, navController)
                                        },
                                        onChatClick = { conv ->
                                            if (NetworkUtils.isNetworkAvailable(context)) {
                                                AgentChatListViewModel.createSingleChat(conv.trtcUserId)
                                                AgentChatListViewModel.goToChatAi(conv.trtcUserId, navController)
                                            } else {
                                                Toast.makeText(context, "网络连接异常，请检查网络设置", Toast.LENGTH_SHORT).show()
                                            }
                                        }
                                    )
                                }
                            }
                            "group" -> {
                                item.groupConversation?.let { group ->
                                    GroupChatItem(
                                        conversation = group,
                                        onGroupAvatarClick = { conv ->
                                            GroupChatListViewModel.goToGroupDetail(conv, navController)
                                        },
                                        onChatClick = { conv ->
                                            if (NetworkUtils.isNetworkAvailable(context)) {
                                                GroupChatListViewModel.goToChat(conv, navController)
                                            } else {
                                                Toast.makeText(context, "网络连接异常，请检查网络设置", Toast.LENGTH_SHORT).show()
                                            }
                                        }
                                    )
                                }
                            }
                            "friend" -> {
                                item.friendConversation?.let { friend ->
                                    FriendChatItem(
                                        conversation = friend,
                                        onUserAvatarClick = { conv ->
                                            FriendChatListViewModel.goToUserDetail(conv, navController)
                                        },
                                        onChatClick = { conv ->
                                            if (NetworkUtils.isNetworkAvailable(context)) {
                                                FriendChatListViewModel.goToChat(conv, navController)
                                            } else {
                                                Toast.makeText(context, "网络连接异常，请检查网络设置", Toast.LENGTH_SHORT).show()
                                            }
                                        }
                                    )
                                }
                            }
                        }

                        // 分隔线
//                        if (index < allConversations.size - 1) {
//                            HorizontalDivider(
//                                modifier = Modifier.padding(horizontal = 24.dp),
//                                color = AppColors.divider
//                            )
//                        }
                    }

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

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

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

