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.AccountService
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.RoomService
import com.aiosman.ravenow.data.RoomServiceImpl
import com.aiosman.ravenow.data.UserService
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.data.api.ApiClient
import kotlinx.coroutines.launch

object AddGroupMemberViewModel : ViewModel() {
    val accountService: AccountService = AccountServiceImpl()
    val userService: UserService = UserServiceImpl()
    val roomService: RoomService = RoomServiceImpl()

    // 状态管理
    var isLoading by mutableStateOf(false)
    var errorMessage by mutableStateOf<String?>(null)
    var groupName: String? = null
    var trtcId: String? = null
    var roomId: Int? = null

    // 添加成员到群聊
    suspend fun addMembersToGroup(
        selectedMembers: List<GroupMember>
    ): Boolean {
        return try {
            isLoading = true

            // 验证房间标识
            if (trtcId == null && roomId == null) {
                isLoading = false
                val errorMsg = "房间标识不能为空"
                showToast(errorMsg)
                return false
            }

            // 根据isAi属性分别获取用户和智能体的OpenID列表
            val userOpenIds = selectedMembers.filter { !it.isAi }.map { it.id }
            val agentOpenIds = selectedMembers.filter { it.isAi }.map { it.id }

            var allSuccess = true
            var errorMessages = mutableListOf<String>()

            // 添加用户到房间
            if (userOpenIds.isNotEmpty()) {
                try {
                    val userResult = roomService.addUserToRoom(
                        roomId = roomId,
                        trtcId = trtcId,
                        openIds = userOpenIds
                    )
                    
                    // 检查添加结果
                    if (userResult.failedCount > 0) {
                        val failedUsers = userResult.failedItems.joinToString(", ") { it.userId }
                        errorMessages.add("部分用户添加失败: $failedUsers")
                    }
                    
                    if (userResult.successCount == 0 && userResult.failedCount > 0) {
                        allSuccess = false
                    }
                } catch (e: Exception) {
                    allSuccess = false
                    errorMessages.add("添加用户失败: ${e.message}")
                }
            }

            // 添加智能体到房间
            if (agentOpenIds.isNotEmpty()) {
                try {
                    val agentResult = roomService.addAgentToRoom(
                        roomId = roomId,
                        trtcId = trtcId,
                        agentOpenIds = agentOpenIds
                    )
                    
                    // 检查添加结果
                    if (agentResult.failedCount > 0) {
                        val failedAgents = agentResult.failedItems.joinToString(", ") { it.agentOpenId }
                        errorMessages.add("部分智能体添加失败: $failedAgents")
                    }
                    
                    if (agentResult.successCount == 0 && agentResult.failedCount > 0) {
                        allSuccess = false
                    }
                } catch (e: Exception) {
                    allSuccess = false
                    errorMessages.add("添加智能体失败: ${e.message}")
                }
            }

            isLoading = false

            if (allSuccess) {
                if (errorMessages.isNotEmpty()) {
                    // 有部分失败，但至少有一些成功
                    showToast(errorMessages.joinToString("\n"))
                }
                true
            } else {
                // 全部失败
                val errorMsg = if (errorMessages.isNotEmpty()) {
                    errorMessages.joinToString("\n")
                } else {
                    "添加成员失败"
                }
                showToast(errorMsg)
                false
            }
        } catch (e: Exception) {
            isLoading = false
            val errorMsg = "添加成员失败: ${e.message}"
            showToast(errorMsg)
            false
        }
    }

    private fun showToast(message: String) {
        Log.w("AddGroupMemberViewModel", 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)
        }
    }
}

// 支持roomId的AI智能体列表ViewModel
class AddMemberAiAgentListViewModel(private val excludeRoomId: Int? = null) : ViewModel() {
    private val accountService: AccountService = AccountServiceImpl()
    
    var aiAgents by mutableStateOf<List<GroupMember>>(emptyList())
        private set
    
    var isLoading by mutableStateOf(false)
        private set
    
    var isRefreshing by mutableStateOf(false)
        private set
    
    var isLoadingMore by mutableStateOf(false)
        private set
    
    var currentPage by mutableStateOf(1)
        private set
    
    var hasMoreData by mutableStateOf(true)
        private set
    
    var errorMessage by mutableStateOf<String?>(null)
        private set
    
    private val pageSize = 20
    
    init {
        loadAgents(1)
    }
    
    fun loadAgents(page: Int, isRefresh: Boolean = false, searchText: String = "") {
        viewModelScope.launch {
            try {
                if (isRefresh) {
                    isRefreshing = true
                } else if (page == 1) {
                    isLoading = true
                } else {
                    isLoadingMore = true
                }
                
                errorMessage = null
                
                val response = accountService.getAgent(page, pageSize, excludeRoomId = excludeRoomId, title = if (searchText.isNotEmpty()) searchText else null, desc = if (searchText.isNotEmpty()) searchText else null)
                if (response.isSuccessful && response.body() != null) {
                    val agentData = response.body()!!
                    val newAgents: List<GroupMember> = agentData.data.list.map { agent ->
                        GroupMember(
                            id = agent.openId,
                            name = agent.title,
                            avatar = "${ApiClient.BASE_API_URL+"/outside"}${agent.avatar}"+"?token="+"${AppStore.token}",
                            isAi = true
                        )
                    }
                    
                    if (isRefresh || page == 1) {
                        aiAgents = newAgents
                        currentPage = 1
                    } else {
                        aiAgents = aiAgents + newAgents
                        currentPage = page
                    }
                    
                    hasMoreData = newAgents.size >= pageSize
                } else {
                    errorMessage = "获取AI智能体列表失败: ${response.message()}"
                }
            } catch (e: Exception) {
                errorMessage = "获取AI智能体列表失败: ${e.message}"
            } finally {
                isLoading = false
                isRefreshing = false
                isLoadingMore = false
            }
        }
    }
    
    fun refresh(searchText: String = "") {
        loadAgents(1, true, searchText)
    }
    
    fun loadMore(searchText: String = "") {
        if (hasMoreData && !isLoadingMore && !isLoading) {
            loadAgents(currentPage + 1, false, searchText)
        }
    }
    
    fun clearError() {
        errorMessage = null
    }
    
    fun getFilteredAgents(searchText: String): List<GroupMember> {
        return if (searchText.isEmpty()) {
            aiAgents
        } else {
            aiAgents.filter { it.name.contains(searchText, ignoreCase = true) }
        }
    }
}

// 支持roomId的朋友列表ViewModel
class AddMemberFriendListViewModel(private val roomId: Int? = null) : ViewModel() {
    private val userService: UserService = UserServiceImpl()
    
    var friends by mutableStateOf<List<GroupMember>>(emptyList())
        private set
    
    var isLoading by mutableStateOf(false)
        private set
    
    var isRefreshing by mutableStateOf(false)
        private set
    
    var isLoadingMore by mutableStateOf(false)
        private set
    
    var currentPage by mutableStateOf(1)
        private set
    
    var hasMoreData by mutableStateOf(true)
        private set
    
    var errorMessage by mutableStateOf<String?>(null)
        private set
    
    private val pageSize = 20
    
    init {
        loadFriends(1)
    }
    
    fun loadFriends(page: Int, isRefresh: Boolean = false, searchText: String = "") {
        viewModelScope.launch {
            try {
                if (isRefresh) {
                    isRefreshing = true
                } else if (page == 1) {
                    isLoading = true
                } else {
                    isLoadingMore = true
                }
                
                errorMessage = null
                
                val userData = userService.getUsers(pageSize, page, nickname = if (searchText.isNotEmpty()) searchText else null, roomId = roomId)
                val newFriends: List<GroupMember> = userData.list.map { user ->
                    GroupMember(
                        id = user.chatAIId,
                        name = user.nickName,
                        avatar = user.avatar,
                        isAi = false
                    )
                }
                
                if (isRefresh || page == 1) {
                    friends = newFriends
                    currentPage = 1
                } else {
                    friends = friends + newFriends
                    currentPage = page
                }
                
                hasMoreData = newFriends.size >= pageSize
            } catch (e: Exception) {
                errorMessage = "获取朋友列表失败: ${e.message}"
            } finally {
                isLoading = false
                isRefreshing = false
                isLoadingMore = false
            }
        }
    }
    
    fun refresh(searchText: String = "") {
        loadFriends(1, true, searchText)
    }
    
    fun loadMore(searchText: String = "") {
        if (hasMoreData && !isLoadingMore && !isLoading) {
            loadFriends(currentPage + 1, false, searchText)
        }
    }
    
    fun clearError() {
        errorMessage = null
    }
    
    fun getFilteredFriends(searchText: String): List<GroupMember> {
        return if (searchText.isEmpty()) {
            friends
        } else {
            friends.filter { it.name.contains(searchText, ignoreCase = true) }
        }
    }
}

