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.ChatState
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.data.RoomService
import com.aiosman.ravenow.data.RoomServiceImpl
import com.aiosman.ravenow.data.parseErrorResponse
import com.aiosman.ravenow.data.PointService
import com.aiosman.ravenow.entity.RoomRuleEntity
import com.aiosman.ravenow.entity.RoomRuleQuotaEntity
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.flow.first
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)
    var isAddingMemory by mutableStateOf(false)
    var addMemoryError by mutableStateOf<String?>(null)
    var addMemorySuccess by mutableStateOf(false)
    val notificationStrategy get() = chatNotification?.strategy ?: "default"
    
    // 记忆管理相关状态
    var memoryQuota by mutableStateOf<RoomRuleQuotaEntity?>(null)
    var memoryList by mutableStateOf<List<RoomRuleEntity>>(emptyList())
    var isLoadingMemory by mutableStateOf(false)
    var memoryError by mutableStateOf<String?>(null)
    
    // 房间规则服务
    private val roomService: RoomService = RoomServiceImpl()
    
    // 群可见性相关状态
    var privateGroupCost by mutableStateOf<Int?>(null)
    var pointsBalance by mutableStateOf<Int?>(null)
    var isLoadingVisibility by mutableStateOf(false)
    var isUpdatingVisibility by mutableStateOf(false)
    
    // 群记忆相关状态
    var addMemoryCost by mutableStateOf<Int?>(null)
    init {
        loadGroupInfo()
        loadVisibilityInfo()
        loadMemoryCost()
    }
    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(),
                        trtcType = it.trtcType ?: "Public",
                        privateFeePaid = it.privateFeePaid ?: false
                    )
                }

            } catch (e: Exception) {
                error = e.message ?: "加载失败"
            } finally {
                isLoading = false
            }
        }
    }
    
    /**
     * 添加群记忆（房间规则）
     * @param memoryText 记忆内容
     */
    fun addGroupMemory(memoryText: String) {
        viewModelScope.launch {
            try {
                isAddingMemory = true
                addMemoryError = null
                addMemorySuccess = false
                
                // 使用房间规则接口创建群记忆
                roomService.createRoomRule(
                    rule = memoryText,
                    trtcId = groupId
                )
                
                addMemorySuccess = true
                Log.d("GroupChatInfoViewModel", "群记忆添加成功")
                // 刷新记忆列表和配额
                loadMemoryQuota()
                loadMemoryList()
            } catch (e: Exception) {
                addMemoryError = e.message ?: "添加群记忆失败"
                Log.e("GroupChatInfoViewModel", "添加群记忆失败: ${e.message}", e)
            } finally {
                isAddingMemory = false
            }
        }
    }
    
    /**
     * 获取记忆配额信息（房间规则配额）
     */
    fun loadMemoryQuota() {
        viewModelScope.launch {
            try {
                isLoadingMemory = true
                memoryError = null
                
                // 使用房间规则接口获取配额
                memoryQuota = roomService.getRoomRuleQuota(trtcId = groupId)
            } catch (e: Exception) {
                memoryError = e.message ?: "获取配额信息失败"
                Log.e("GroupChatInfoViewModel", "获取配额信息失败: ${e.message}", e)
            } finally {
                isLoadingMemory = false
            }
        }
    }
    
    /**
     * 获取记忆列表（房间规则列表）
     */
    fun loadMemoryList(page: Int = 1, pageSize: Int = 20) {
        viewModelScope.launch {
            try {
                isLoadingMemory = true
                memoryError = null
                
                // 使用房间规则接口获取列表
                val result = roomService.getRoomRuleList(
                    trtcId = groupId,
                    page = page,
                    pageSize = pageSize
                )
                memoryList = result.list
            } catch (e: Exception) {
                memoryError = e.message ?: "获取记忆列表失败"
                Log.e("GroupChatInfoViewModel", "获取记忆列表失败: ${e.message}", e)
            } finally {
                isLoadingMemory = false
            }
        }
    }
    
    /**
     * 删除记忆（房间规则）
     */
    fun deleteMemory(ruleId: Int) {
        viewModelScope.launch {
            try {
                isLoadingMemory = true
                memoryError = null
                
                // 使用房间规则接口删除
                roomService.deleteRoomRule(ruleId)
                
                // 刷新记忆列表和配额
                loadMemoryQuota()
                loadMemoryList()
            } catch (e: Exception) {
                memoryError = e.message ?: "删除记忆失败"
                Log.e("GroupChatInfoViewModel", "删除记忆失败: ${e.message}", e)
            } finally {
                isLoadingMemory = false
            }
        }
    }
    
    /**
     * 更新记忆（房间规则）
     */
    fun updateMemory(ruleId: Int, newRuleText: String) {
        viewModelScope.launch {
            try {
                isLoadingMemory = true
                memoryError = null
                
                // 使用房间规则接口更新
                roomService.updateRoomRule(
                    id = ruleId,
                    rule = newRuleText
                )
                
                // 刷新记忆列表和配额
                loadMemoryQuota()
                loadMemoryList()
            } catch (e: Exception) {
                memoryError = e.message ?: "更新记忆失败"
                Log.e("GroupChatInfoViewModel", "更新记忆失败: ${e.message}", e)
            } finally {
                isLoadingMemory = false
            }
        }
    }
    
    /**
     * 加载群可见性相关信息（价格和积分余额）
     */
    fun loadVisibilityInfo() {
        viewModelScope.launch {
            try {
                isLoadingVisibility = true
                
                // 获取积分规则中的私密群组价格
                PointService.refreshPointsRules()
                val rules = PointService.pointsRules.first()
                val roomPrivateRule = rules?.sub?.get(PointService.PointsRuleKey.ROOM_PRIVATE)
                privateGroupCost = when (roomPrivateRule) {
                    is PointService.RuleAmount.Fixed -> roomPrivateRule.value
                    is PointService.RuleAmount.Range -> roomPrivateRule.min
                    null -> null
                }
                
                // 获取积分余额
                PointService.refreshMyPointsBalance(includeStatistics = false)
                val balance = PointService.pointsBalance.first()
                pointsBalance = balance?.balance
            } catch (e: Exception) {
                Log.e("GroupChatInfoViewModel", "加载可见性信息失败: ${e.message}", e)
            } finally {
                isLoadingVisibility = false
            }
        }
    }
    
    /**
     * 更新群可见性
     * @param isPrivate 是否设置为私密群组
     */
    fun updateVisibility(isPrivate: Boolean) {
        viewModelScope.launch {
            try {
                isUpdatingVisibility = true
                // TODO: 实现更新房间可见性的接口调用
                // 暂时留空
                
                // 更新成功后刷新群信息和积分余额
                loadGroupInfo()
                loadVisibilityInfo()
            } catch (e: Exception) {
                Log.e("GroupChatInfoViewModel", "更新可见性失败: ${e.message}", e)
            } finally {
                isUpdatingVisibility = false
            }
        }
    }
    
    /**
     * 加载添加群记忆的价格
     */
    fun loadMemoryCost() {
        viewModelScope.launch {
            try {
                // 获取积分规则中的房间记忆价格（群聊记忆，区别于 Agent 记忆）
                PointService.refreshPointsRules()
                val rules = PointService.pointsRules.first()
                val roomMemoryRule = rules?.sub?.get(PointService.PointsRuleKey.SPEND_ROOM_MEMORY)
                addMemoryCost = when (roomMemoryRule) {
                    is PointService.RuleAmount.Fixed -> roomMemoryRule.value
                    is PointService.RuleAmount.Range -> roomMemoryRule.min
                    else -> null
                }
            } catch (e: Exception) {
                Log.e("GroupChatInfoViewModel", "加载记忆价格失败: ${e.message}", e)
            }
        }
    }
}