package com.aiosman.ravenow.ui.group

import android.content.Context
import android.icu.util.Calendar
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.paging.PagingData
import androidx.paging.map
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.ConstVars
import com.aiosman.ravenow.data.AccountNotice
import com.aiosman.ravenow.data.AccountService
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.PointService
import com.aiosman.ravenow.data.UserService
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.R
import com.aiosman.ravenow.entity.CommentEntity
import com.aiosman.ravenow.exp.formatChatTime
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.navigateToChat
import com.aiosman.ravenow.utils.TrtcHelper
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlin.coroutines.suspendCoroutine

object CreateGroupChatViewModel : ViewModel() {
    val accountService: AccountService = AccountServiceImpl()
    val userService: UserService = UserServiceImpl()

    // 状态管理
    var isLoading by mutableStateOf(false)
    var errorMessage by mutableStateOf<String?>(null)
    var showConfirmDialog by mutableStateOf(false)

    // 创建群聊
    suspend fun createGroupChat(
        groupName: String,
        selectedMembers: List<GroupMember>,
        context: Context
    ): Boolean {
        return try {
            isLoading = true

            // 根据isAi属性分别获取userIds和promptIds
            val userIds = selectedMembers.filter { !it.isAi }.map { it.id }
            val promptIds = selectedMembers.filter { it.isAi }.map { it.id }

            val response = accountService.createGroupChat(groupName, userIds, promptIds)
            if (response.isSuccessful && response.body() != null) {
                isLoading = false
                true
            } else {
                isLoading = false
                val errorMsg = context.getString(R.string.create_group_chat_failed, response.message() ?: "")
                showToast(errorMsg)
                false
            }
        } catch (e: Exception) {
            isLoading = false
            val errorMsg = context.getString(R.string.create_group_chat_failed, e.message ?: "")
            showToast(errorMsg)
            false
        }
    }

    private fun showToast(message: String) {
        errorMessage = message
        viewModelScope.launch {
            delay(3000)
            errorMessage = null
        }
    }

    // 显示错误信息（公开方法）
    fun showError(message: String) {
        showToast(message)
    }

    // 清除错误信息
    fun clearError() {
        errorMessage = null
    }

    // 添加成员到选中列表
    fun addSelectedMember(member: GroupMember, selectedMemberIds: Set<String>, selectedMembers: List<GroupMember>): Pair<Set<String>, List<GroupMember>> {
        val newSelectedMemberIds = selectedMemberIds + member.id
        val newSelectedMembers = if (selectedMembers.none { it.id == member.id }) {
            selectedMembers + member
        } else {
            selectedMembers
        }
        return Pair(newSelectedMemberIds, newSelectedMembers)
    }

    // 从选中列表移除成员
    fun removeSelectedMember(member: GroupMember, selectedMemberIds: Set<String>, selectedMembers: List<GroupMember>): Pair<Set<String>, List<GroupMember>> {
        val newSelectedMemberIds = selectedMemberIds - member.id
        val newSelectedMembers = selectedMembers.filter { it.id != member.id }
        return Pair(newSelectedMemberIds, newSelectedMembers)
    }

    // 切换成员选中状态
    fun toggleMemberSelection(member: GroupMember, selectedMemberIds: Set<String>, selectedMembers: List<GroupMember>): Pair<Set<String>, List<GroupMember>> {
        return if (selectedMemberIds.contains(member.id)) {
            removeSelectedMember(member, selectedMemberIds, selectedMembers)
        } else {
            addSelectedMember(member, selectedMemberIds, selectedMembers)
        }
    }

    /**
     * 获取创建群聊的费用
     * @return 费用金额，如果无法获取则返回 0
     */
    fun getCreateRoomCost(): Int {
        val rules = PointService.pointsRules.value
        val costRule = rules?.sub?.get(PointService.PointsRuleKey.CREATE_ROOM)
        return when (costRule) {
            is PointService.RuleAmount.Fixed -> costRule.value
            is PointService.RuleAmount.Range -> costRule.min // 使用最小值作为默认费用
            null -> 0
        }
    }

    /**
     * 获取当前余额
     * @return 当前余额，如果无法获取则返回 0
     */
    fun getCurrentBalance(): Int {
        return PointService.pointsBalance.value?.balance ?: 0
    }

    /**
     * 计算消耗后余额
     * @param cost 费用
     * @return 消耗后余额
     */
    fun calculateBalanceAfterCost(cost: Int): Int {
        val currentBalance = getCurrentBalance()
        return (currentBalance - cost).coerceAtLeast(0)
    }

    /**
     * 检查余额是否充足
     * @param cost 费用
     * @return 是否充足
     */
    fun isBalanceSufficient(cost: Int): Boolean {
        return getCurrentBalance() >= cost
    }

    /**
     * 显示确认弹窗
     */
    fun showConfirmDialog() {
        showConfirmDialog = true
    }

    /**
     * 隐藏确认弹窗
     */
    fun hideConfirmDialog() {
        showConfirmDialog = false
    }
}
