package com.aiosman.ravenow.ui.chat

import android.content.Context
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.data.api.SendChatAiRequestBody
import io.openim.android.sdk.enums.ConversationType
import io.openim.android.sdk.models.*
import kotlinx.coroutines.launch

class GroupChatViewModel(
    val groupId: String,
    val name: String,
    val avatar: String,
) : BaseChatViewModel() {
    var groupInfo by mutableStateOf<GroupInfo?>(null)
    
    // 群聊特有属性
    var memberCount by mutableStateOf(0)
    var groupName by mutableStateOf("")
    var groupAvatar by mutableStateOf("")
    
    data class GroupInfo(
        val groupId: String,
        val groupName: String,
        val groupAvatar: String,
        val memberCount: Int,
        val ownerId: String
    )
    
    override fun init(context: Context) {
        viewModelScope.launch {
            try {
                getGroupInfo()
                myProfile = accountService.getMyAccountProfile()
                RegistListener(context)
                
                // 获取会话信息，然后加载历史消息
                getOneConversation {
                    fetchHistoryMessage(context)
                }
            } catch (e: Exception) {
                Log.e("GroupChatViewModel", "初始化失败: ${e.message}")
            }
        }
    }
    
    private suspend fun getGroupInfo() {
        // 简化群组信息获取，使用默认信息
        groupInfo = GroupInfo(
            groupId = groupId,
            groupName = name,
            groupAvatar = avatar,
            memberCount = 0,
            ownerId = ""
        )
        groupName = groupInfo?.groupName ?: ""
        groupAvatar = groupInfo?.groupAvatar ?: ""
        memberCount = groupInfo?.memberCount ?: 0
    }

    override fun getConversationParams(): Triple<String, Int, Boolean> {
        // 根据群组类型决定ConversationType，这里假设是普通群聊
        return Triple(groupId, ConversationType.GROUP_CHAT, false)
    }

    override fun getLogTag(): String {
        return "GroupChatViewModel"
    }

    override fun handleNewMessage(message: Message, context: Context): Boolean {
        // 检查是否是当前群聊的消息
        return message.groupID == groupId
    }

    override fun getReceiverInfo(): Pair<String?, String?> {
        return Pair(null, groupId) // (recvID, groupID)
    }

    override fun getMessageAvatar(message: Message): String? {
        // 群聊中，如果是自己发送的消息显示自己的头像，否则为null（由ChatItem处理）
        return if (message.sendID == com.aiosman.ravenow.AppState.profile?.trtcUserId) {
            myProfile?.avatar
        } else {
            null
        }
    }

    override fun onMessageSentSuccess(message: String, sentMessage: Message?) {
        // 群聊特有的处理逻辑
        sendChatAiMessage(message = message, trtcGroupId = groupId)
    }



    fun sendChatAiMessage(
        trtcGroupId: String,
        message: String,
    ) {
        viewModelScope.launch {
            val response = ApiClient.api.sendChatAiMessage(SendChatAiRequestBody(trtcGroupId = trtcGroupId,message = message))
        }
    }

}
