package com.aiosman.ravenow.ui.group

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.ChatState
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.entity.ChatNotification
import com.aiosman.ravenow.entity.GroupInfo
import com.aiosman.ravenow.entity.GroupMember
import com.aiosman.ravenow.ui.index.tabs.profile.MyProfileViewModel
import kotlinx.coroutines.launch

class GroupChatInfoViewModel(
    private val groupId: String
) : ViewModel() {

    var groupInfo by mutableStateOf<GroupInfo?>(null)
    var isLoading by mutableStateOf(false)
    var error by mutableStateOf<String?>(null)
    var chatNotification by mutableStateOf<ChatNotification?>(null)
    val notificationStrategy get() = chatNotification?.strategy ?: "default"
    init {
        loadGroupInfo()
    }
    suspend fun updateNotificationStrategy(strategy: String) {
        val result = ChatState.updateChatNotification(groupId.hashCode(), strategy)
        chatNotification = result
    }


    private fun loadGroupInfo() {
        viewModelScope.launch {
            val notiStrategy = ChatState.getStrategyByTargetTrtcId(groupId)
            chatNotification = notiStrategy
            try {
                isLoading = true
                error = null

                // 调用接口获取群聊详情
                val response = ApiClient.api.getRoomDetail(trtcId = groupId)

                // 使用接口返回的数据
                val room = response.body()?.data
                groupInfo = room?.let {
                    GroupInfo(
                        groupId = groupId,
                        groupName = it.name,
                        groupAvatar = if (it.avatar.isNullOrEmpty()) {
                            // 将 groupId 转换为 Base64
                            val groupIdBase64 = android.util.Base64.encodeToString(
                                groupId.toByteArray(),
                                android.util.Base64.NO_WRAP
                            )
                            "${ApiClient.RETROFIT_URL+"group/avatar?groupIdBase64="}${groupIdBase64}"+"&token="+"${AppStore.token}"
                        } else {
                            "${ApiClient.BASE_API_URL+"/outside"}${it.avatar}"+"?token="+"${AppStore.token}"
                        },
                        memberCount = room.userCount,
                        isCreator = room.creator.userId == MyProfileViewModel.profile?.id.toString()
                    )
                }

            } catch (e: Exception) {
                error = e.message ?: "加载失败"
            } finally {
                isLoading = false
            }
        }
    }
}