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

import android.content.Context
import android.icu.util.Calendar
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.ConstVars
import com.aiosman.ravenow.R
import com.aiosman.ravenow.data.UserService
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.data.api.SingleChatRequestBody
import com.aiosman.ravenow.exp.formatChatTime
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.index.tabs.ai.tabs.mine.MineAgentViewModel.createGroup2ChatAi
import com.aiosman.ravenow.ui.index.tabs.message.MessageListViewModel
import com.aiosman.ravenow.ui.navigateToChatAi
import io.openim.android.sdk.OpenIMClient
import io.openim.android.sdk.listener.OnBase
import io.openim.android.sdk.models.ConversationInfo
import io.openim.android.sdk.models.Message
import kotlinx.coroutines.launch
import kotlin.coroutines.suspendCoroutine
import com.aiosman.ravenow.utils.MessageParser

data class AgentConversation(
    val id: String,
    val trtcUserId: String,
    val nickname: String,
    val lastMessage: String,
    val lastMessageTime: String,
    val avatar: String = "",
    val unreadCount: Int = 0,
    val displayText: String,
    val isSelf: Boolean
) {
    companion object {
        fun convertToAgentConversation(conversation: ConversationInfo, context: Context): AgentConversation {
            val lastMessage = Calendar.getInstance().apply {
                timeInMillis = conversation.latestMsgSendTime
            }
            
            // 解析最新消息
            val (displayText, isSelf) = MessageParser.parseLatestMessage(conversation.latestMsg)
            return AgentConversation(
                id = conversation.conversationID,
                nickname = conversation.showName ?: "",
                lastMessage = displayText, // 使用解析后的显示文本
                lastMessageTime = lastMessage.time.formatChatTime(context),
                avatar = "${ApiClient.BASE_API_URL+"/"}${conversation.faceURL}"+"?token="+"${AppStore.token}".replace("storage/avatars/", "/avatar/"),
                unreadCount = conversation.unreadCount,
                trtcUserId = conversation.userID ?: "",
                displayText = displayText,
                isSelf = isSelf // 使用解析后的发送者信息
            )
        }
    }
}

object AgentChatListViewModel : ViewModel() {
    val userService: UserService = UserServiceImpl()
    var agentChatList by mutableStateOf<List<AgentConversation>>(emptyList())
    var isLoading by mutableStateOf(false)
    var refreshing by mutableStateOf(false)
    var hasNext by mutableStateOf(true)
    var currentPage by mutableStateOf(1)
    var error by mutableStateOf<String?>(null)

    // 计算智能体总未读消息数
    val totalUnreadCount: Int
        get() = agentChatList.sumOf { it.unreadCount }

    private val pageSize = 20

    fun refreshPager(pullRefresh: Boolean = false, context: Context? = null) {
        if (isLoading && !pullRefresh) return
        viewModelScope.launch {
            try {
                isLoading = true
                refreshing = pullRefresh
                error = null
                context?.let { loadAgentChatList(it) }
                currentPage = 1
            } catch (e: Exception) {
                error = e.message ?: context?.getString(R.string.agent_chat_load_failed)
                e.printStackTrace()
            } finally {
                isLoading = false
                refreshing = false
            }
        }
    }

    fun loadMore() {
        if (isLoading || !hasNext) return
        viewModelScope.launch {
            try {
                isLoading = true
                error = null
                // 腾讯IM的会话列表是一次性获取的，这里模拟分页
                // 实际项目中可能需要根据时间戳或其他方式实现真正的分页
                hasNext = false
            } catch (e: Exception) {
                error = ""
                e.printStackTrace()
            } finally {
                isLoading = false
            }
        }
    }

    private suspend fun loadAgentChatList(context: Context) {
        // 检查 OpenIM 是否已登录
        if (!com.aiosman.ravenow.AppState.enableChat) {
            android.util.Log.w("AgentChatListViewModel", "OpenIM 未登录，跳过加载智能体聊天列表")
            return
        }
        
        val result = suspendCoroutine { continuation ->
            // OpenIM 获取所有会话列表
            OpenIMClient.getInstance().conversationManager.getAllConversationList(
                object : OnBase<List<ConversationInfo>> {
                    override fun onSuccess(data: List<ConversationInfo>?) {
                        // 过滤出智能体会话（单聊类型，且可能有特定标识）
                        val agentConversations = data?.filter { conversation ->
                            // 这里需要根据实际业务逻辑来过滤智能体会话
                            // 可能通过会话类型、用户ID前缀、或其他标识来判断
                            conversation.conversationType == 1 // 1 表示单聊
                            // 可以添加更多过滤条件，比如：
                            // && conversation.userID?.startsWith("ai_") == true
                        } ?: emptyList()
                        continuation.resumeWith(Result.success(agentConversations))
                    }

                    override fun onError(code: Int, error: String?) {
                        continuation.resumeWith(Result.failure(Exception("Error $code: $error")))
                    }
                }
            )
        }

        agentChatList = result.map { conversation ->
            AgentConversation.convertToAgentConversation(conversation, context)
        }
    }

    fun goToChatAi(
        conversation: AgentConversation,
        navController: NavHostController
    ) {
        viewModelScope.launch {
            try {
                val profile = userService.getUserProfileByTrtcUserId(conversation.trtcUserId,1)
                navController.navigateToChatAi(profile.id.toString())
            } catch (e: Exception) {
                error = ""
                e.printStackTrace()
            }
        }
    }

    fun goToUserDetail(
        conversation: AgentConversation,
        navController: NavHostController
    ) {
        viewModelScope.launch {
            try {
                val profile = userService.getUserProfileByTrtcUserId(conversation.trtcUserId,1)
                navController.navigate(
                    NavigationRoute.AccountProfile.route.replace(
                        "{id}",
                        profile.id.toString()
                    )
                )
            } catch (e: Exception) {
                error = ""
                e.printStackTrace()
            }
        }
    }

    fun refreshConversation(context: Context, userId: String) {
        viewModelScope.launch {
            loadAgentChatList(context)
        }
    }
    fun createSingleChat(
        trtcId: String,
    ) {
        viewModelScope.launch {
            val response = ApiClient.api.createSingleChat(SingleChatRequestBody(agentTrtcId = trtcId))
        }

    }
    fun goToChatAi(
        openId: String,
        navController: NavHostController
    ) {
        viewModelScope.launch {
            val profile = MessageListViewModel.userService.getUserProfileByTrtcUserId(openId,1)
            navController.navigateToChatAi(profile.id.toString())
        }
    }
}
