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.data.UserService
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.data.api.GroupChatRequestBody
import com.aiosman.ravenow.exp.formatChatTime
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.navigateToChat
import com.aiosman.ravenow.ui.navigateToGroupChat
import com.aiosman.ravenow.ui.navigateToGroupInfo
// OpenIM SDK 导入
import io.openim.android.sdk.OpenIMClient
import io.openim.android.sdk.listener.OnAdvanceMsgListener
import io.openim.android.sdk.listener.OnBase
import io.openim.android.sdk.listener.OnConversationListener
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 GroupConversation(
    val id: String,
    val groupId: String,
    val groupName: String,
    val lastMessage: String,
    val lastMessageTime: String,
    val avatar: String = "",
    val unreadCount: Int = 0,
    val displayText: String,
    val isSelf: Boolean,
    val memberCount: Int = 0
) {
    companion object {
        fun convertToGroupConversation(conversation: ConversationInfo, context: Context): GroupConversation {
            val lastMessage = Calendar.getInstance().apply {
                timeInMillis = conversation.latestMsgSendTime
            }
            
            // 解析最新消息
            val (displayText, isSelf) = MessageParser.parseLatestMessage(conversation.latestMsg)

            return GroupConversation(
                id = conversation.conversationID,
                groupId = conversation.groupID ?: "",
                groupName = conversation.showName ?: "",
                lastMessage = displayText, // 使用解析后的显示文本
                lastMessageTime = lastMessage.time.formatChatTime(context),
                avatar = if (conversation.faceURL.isNullOrEmpty()) {
                    // 将 groupId 转换为 Base64
                    val groupIdBase64 = android.util.Base64.encodeToString(
                        (conversation.groupID ?: "").toByteArray(),
                        android.util.Base64.NO_WRAP
                    )
                    "${ApiClient.RETROFIT_URL+"group/avatar?groupIdBase64="}${groupIdBase64}"+"&token="+"${AppStore.token}"
                } else {
                    "${ApiClient.BASE_API_URL+"/outside/rooms/avatar/"}${conversation.faceURL}"+"?token="+"${AppStore.token}"
                },
                unreadCount = conversation.unreadCount,
                displayText = displayText,
                isSelf = isSelf, // 使用解析后的发送者信息
                memberCount = 0 // TODO: 获取群组成员数量
            )
        }
    }
}

object GroupChatListViewModel : ViewModel() {
    val userService: UserService = UserServiceImpl()
    var groupChatList by mutableStateOf<List<GroupConversation>>(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() = groupChatList.sumOf { it.unreadCount }

    private val pageSize = 20

    // 消息监听器
    private var messageListener: OnAdvanceMsgListener? = null
    private var conversationListener: OnConversationListener? = null

    fun refreshPager(pullRefresh: Boolean = false, context: Context? = null) {
        if (isLoading && !pullRefresh) return
        viewModelScope.launch {
            try {
                isLoading = true
                refreshing = pullRefresh
                error = null
                context?.let { loadGroupChatList(it) }
                currentPage = 1
            } catch (e: Exception) {
                error = ""
                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 loadGroupChatList(context: Context) {
        // 检查 OpenIM 是否已登录
        if (!com.aiosman.ravenow.AppState.enableChat) {
            android.util.Log.w("GroupChatListViewModel", "OpenIM 未登录，跳过加载群聊列表")
            return
        }
        
        val result = suspendCoroutine { continuation ->
            // OpenIM 获取所有会话列表
            OpenIMClient.getInstance().conversationManager.getAllConversationList(
                object : OnBase<List<ConversationInfo>> {
                    override fun onSuccess(data: List<ConversationInfo>?) {
                        continuation.resumeWith(Result.success(data ?: emptyList()))
                    }

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

        // 过滤出群聊会话（群聊类型）
        val filteredConversations = result.filter { conversation ->
            // 2 表示群聊类型
            conversation.conversationType == 2
        }

        groupChatList = filteredConversations.map { conversation ->
            GroupConversation.convertToGroupConversation(conversation, context)
        }
    }

    fun createGroupChat(
        trtcGroupId: String,
    ) {
        viewModelScope.launch {
            val response = ApiClient.api.createGroupChatAi(trtcGroupId = trtcGroupId)
        }

    }

    fun goToChat(
        conversation: GroupConversation,
        navController: NavHostController
    ) {
        viewModelScope.launch {
            try {
                createGroupChat(trtcGroupId = conversation.groupId)
                // 群聊直接使用群ID进行导航
                navController.navigateToGroupChat(conversation.groupId, conversation.groupName, conversation.avatar)
            } catch (e: Exception) {
                error = ""
                e.printStackTrace()
            }
        }
    }

    fun goToGroupDetail(
        conversation: GroupConversation,
        navController: NavHostController
    ) {
        viewModelScope.launch {
            try {
                // 导航到群聊详情页面
                navController.navigateToGroupInfo(conversation.groupId)
            } catch (e: Exception) {
                error = ""
                e.printStackTrace()
            }
        }
    }

    fun refreshConversation(context: Context, groupId: String) {
        viewModelScope.launch {
            loadGroupChatList(context)
        }
    }

    // 初始化消息监听器
    fun initMessageListener(context: Context) {
        // 消息监听器 - 监听新消息
        messageListener = object : OnAdvanceMsgListener {
            override fun onRecvNewMessage(msg: io.openim.android.sdk.models.Message?) {
                msg?.let { message ->
                    if (!message.groupID.isNullOrEmpty()) {
                        // 收到群聊消息，刷新群聊列表
                        android.util.Log.i("GroupChatList", "收到群聊消息，刷新列表")
                        refreshGroupChatList(context)
                    }
                }
            }
        }

        // 会话监听器 - 监听会话变化
        conversationListener = object : OnConversationListener {
            override fun onConversationChanged(conversationList: List<ConversationInfo>?) {
                // 会话发生变化，刷新群聊列表
                conversationList?.let { conversations ->
                    val hasGroupConversation = conversations.any { it.conversationType == 2 }
                    if (hasGroupConversation) {
                        android.util.Log.i("GroupChatList", "群聊会话发生变化，刷新列表")
                        refreshGroupChatList(context)
                    }
                }
            }

            override fun onNewConversation(conversationList: List<ConversationInfo>?) {
                // 新增会话，刷新群聊列表
                conversationList?.let { conversations ->
                    val hasGroupConversation = conversations.any { it.conversationType == 2 }
                    if (hasGroupConversation) {
                        android.util.Log.i("GroupChatList", "新增群聊会话，刷新列表")
                        refreshGroupChatList(context)
                    }
                }
            }
        }

        // 注册监听器
        OpenIMClient.getInstance().messageManager.setAdvancedMsgListener(messageListener)
        OpenIMClient.getInstance().conversationManager.setOnConversationListener(conversationListener)
    }

    // 移除消息监听器
    fun removeMessageListener() {
        // OpenIM SDK 不需要显式移除监听器，只需要设置为 null
        messageListener = null
        conversationListener = null
    }

    // 刷新群聊列表
    private fun refreshGroupChatList(context: Context) {
        viewModelScope.launch {
            try {
                loadGroupChatList(context)
            } catch (e: Exception) {
                android.util.Log.e("GroupChatList", "刷新群聊列表失败: ${e.message}")
            }
        }
    }


}
