package com.aiosman.ravenow.ui.group

import android.util.Log
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.data.api.ApiClient
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 GroupMembersViewModel(
    private val groupId: String
) : ViewModel() {

    var groupInfo by mutableStateOf<GroupInfo?>(null)
    var currentUserMember by mutableStateOf<GroupMember?>(null)
    var members by mutableStateOf<List<GroupMember>>(emptyList())
    var isLoading by mutableStateOf(false)
    var error by mutableStateOf<String?>(null)
    var requireApproval by mutableStateOf(true) // 默认开启
    var roomId by mutableStateOf<Int?>(null)
    
    init {
        loadGroupMembers()
    }
    
    private fun loadGroupMembers() {
        viewModelScope.launch {
            try {
                isLoading = true
                error = null
                
                // 调用接口获取群聊详情
                val response = ApiClient.api.getRoomDetail(trtcId = groupId)
                
                if (response.isSuccessful && response.body() != null) {
                    val room = response.body()!!.data
                    
                    // 保存roomId
                    roomId = room.id
                    
                    // 设置群信息
                    groupInfo = GroupInfo(
                        groupId = groupId,
                        groupName = room.name,
                        groupAvatar = if (room.avatar.isNullOrEmpty()) {
                            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${room.avatar}?token=${AppStore.token}"
                        },
                        memberCount = room.userCount,
                        isCreator = room.creator.userId == MyProfileViewModel.profile?.id.toString()
                    )
                    
                    // 获取当前用户ID
                    val currentUserId = MyProfileViewModel.profile?.id.toString()
                    
                    // 转换成员列表
                    val allMembers = room.users.map { user ->
                        val avatarUrl = if (user.profile.avatar.isNullOrEmpty()) {
                            ""
                        } else {
                            // 与动态列表和关注列表一致，使用 BASE_SERVER 构建头像URL，不需要token
                            "${ApiClient.BASE_SERVER}${user.profile.avatar}"
                        }
                        
                        GroupMember(
                            userId = user.userId,
                            nickname = user.profile.nickname.ifEmpty { user.profile.username },
                            avatar = avatarUrl,
                            isOwner = user.userId == room.creator.userId
                        )
                    }
                    
                    // 分离当前用户和其他成员
                    currentUserMember = allMembers.find { it.userId == currentUserId }
                    members = allMembers.filter { it.userId != currentUserId }
                    
                } else {
                    error = "获取群成员列表失败"
                }
            } catch (e: Exception) {
                error = e.message ?: "加载失败"
                Log.e("GroupMembersViewModel", "加载群成员失败", e)
            } finally {
                isLoading = false
            }
        }
    }
    
    fun refresh() {
        loadGroupMembers()
    }
    
    fun deleteMember(memberId: String) {
        viewModelScope.launch {
            try {
                // TODO: 实现删除成员的API调用
                // 删除成功后刷新列表
                loadGroupMembers()
            } catch (e: Exception) {
                error = e.message ?: "删除成员失败"
                Log.e("GroupMembersViewModel", "删除成员失败", e)
            }
        }
    }
}

