package com.aiosman.ravenow.ui.group

import android.graphics.Bitmap
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.entity.GroupInfo
import kotlinx.coroutines.launch

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

    var groupInfo by mutableStateOf<GroupInfo?>(null)
    var groupName by mutableStateOf("")
    var groupIconBitmap by mutableStateOf<Bitmap?>(null)
    var groupAvatarBitmap by mutableStateOf<Bitmap?>(null)
    var isLoading by mutableStateOf(false)
    var error by mutableStateOf<String?>(null)

    init {
        loadGroupInfo()
    }

    fun loadGroupInfo() {
        viewModelScope.launch {
            try {
                isLoading = true
                error = null
                // 直接调用 API 加载群信息
                val response = com.aiosman.ravenow.data.api.ApiClient.api.getRoomDetail(trtcId = groupId)
                val room = response.body()?.data
                groupInfo = room?.let {
                    com.aiosman.ravenow.entity.GroupInfo(
                        groupId = groupId,
                        groupName = it.name,
                        groupAvatar = if (it.avatar.isNullOrEmpty()) {
                            val groupIdBase64 = android.util.Base64.encodeToString(
                                groupId.toByteArray(),
                                android.util.Base64.NO_WRAP
                            )
                            "${com.aiosman.ravenow.data.api.ApiClient.RETROFIT_URL}group/avatar?groupIdBase64=$groupIdBase64&token=${com.aiosman.ravenow.AppStore.token}"
                        } else {
                            "${com.aiosman.ravenow.data.api.ApiClient.BASE_API_URL}/outside${it.avatar}?token=${com.aiosman.ravenow.AppStore.token}"
                        },
                        memberCount = room.userCount,
                        isCreator = room.creator.userId == com.aiosman.ravenow.ui.index.tabs.profile.MyProfileViewModel.profile?.id.toString()
                    )
                }
                groupInfo?.let {
                    groupName = it.groupName
                }
            } catch (e: Exception) {
                error = e.message ?: "加载失败"
            } finally {
                isLoading = false
            }
        }
    }

    fun updateGroupName(newName: String) {
        groupName = newName
    }

    fun setGroupIcon(bitmap: Bitmap) {
        groupIconBitmap = bitmap
    }

    fun setGroupAvatar(bitmap: Bitmap) {
        groupAvatarBitmap = bitmap
    }
}

