package com.aiosman.ravenow.ui.index.tabs.ai.tabs.hot

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.NavHostController
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.data.ServiceException
import com.aiosman.ravenow.data.api.SingleChatRequestBody
import com.aiosman.ravenow.entity.AgentEntity
import com.aiosman.ravenow.ui.index.tabs.ai.tabs.mine.MineAgentViewModel.createGroup2ChatAi
import com.aiosman.ravenow.ui.index.tabs.message.MessageListViewModel.userService
import com.aiosman.ravenow.ui.NavigationRoute
import kotlinx.coroutines.launch

object HotAgentViewModel : ViewModel() {
    var agentList by mutableStateOf<List<AgentEntity>>(emptyList())
    var refreshing by mutableStateOf(false)
    var isLoading by mutableStateOf(false)
    var hasNext by mutableStateOf(true)
    var currentPage by mutableStateOf(1)
    var error by mutableStateOf<String?>(null)
    
    // 记录已预加载的图片ID，避免重复加载
    private val preloadedImageIds = mutableSetOf<Int>()
    
    private val pageSize = 20
    
    init {
        // 延迟初始化，避免在页面切换时立即加载
        // refreshPager()
    }
    
    fun refreshPager(pullRefresh: Boolean = false) {
        if (isLoading && !pullRefresh) return
        
        viewModelScope.launch {
            try {
                isLoading = true
                refreshing = pullRefresh
                error = null
                
                // 清除预加载记录，强制重新加载图片
                if (pullRefresh) {
                    clearPreloadedImages()
                }
                
                val response = ApiClient.api.getAgent(
                    page = 1,
                    pageSize = pageSize
                )
                
                val body = response.body()
                if (body != null) {
                    val newAgents = body.data.list.map { it.toAgentEntity() }
                    // 只有在列表为空或者是下拉刷新时才替换整个列表
                    if (agentList.isEmpty() || pullRefresh) {
                        agentList = newAgents
                    } else {
                        // 否则只添加新的智能体
                        val existingIds = agentList.map { it.id }.toSet()
                        val newAgentsToAdd = newAgents.filter { it.id !in existingIds }
                        if (newAgentsToAdd.isNotEmpty()) {
                            agentList = agentList + newAgentsToAdd
                        }
                    }
                    currentPage = 1
                    hasNext = newAgents.size == pageSize
                } else {
                    throw ServiceException("Failed to load agents")
                }
            } catch (e: Exception) {
                error = e.message ?: "加载失败"
                e.printStackTrace()
            } finally {
                isLoading = false
                refreshing = false
            }
        }
    }
    
    fun loadMore() {
        if (isLoading || !hasNext) return
        
        viewModelScope.launch {
            try {
                isLoading = true
                error = null
                
                val response = ApiClient.api.getAgent(
                    page = currentPage + 1,
                    pageSize = pageSize
                )
                
                val body = response.body()
                if (body != null) {
                    val newAgents = body.data.list.map { it.toAgentEntity() }
                    agentList = agentList + newAgents
                    currentPage += 1
                    hasNext = newAgents.size == pageSize
                } else {
                    throw ServiceException("Failed to load more agents")
                }
            } catch (e: Exception) {
                error = e.message ?: "加载更多失败"
                e.printStackTrace()
            } finally {
                isLoading = false
            }
        }
    }
    fun createSingleChat(
        openId: String,
    ) {
        viewModelScope.launch {
            val response = ApiClient.api.createSingleChat(SingleChatRequestBody(agentOpenId = openId))
        }

    }
    fun goToChatAi(
        openId: String,
        navController: NavHostController
    ) {
        viewModelScope.launch {
            val profile = userService.getUserProfileByOpenId(openId)
            createGroup2ChatAi(profile.trtcUserId,"ai_group",navController,profile.id)
        }
    }
    
    fun goToProfile(
        openId: String,
        navController: NavHostController
    ) {
        viewModelScope.launch {
            try {
                val profile = userService.getUserProfileByOpenId(openId)
                // 从Agent列表点击进去的一定是智能体，直接传递isAiAccount = true
                navController.navigate(
                    NavigationRoute.AccountProfile.route
                        .replace("{id}", profile.id.toString())
                        .replace("{isAiAccount}", "true")
                )
            } catch (e: Exception) {
                // swallow error to avoid crash on navigation attempt failures
            }
        }
    }
    
    // 预加载图片，避免滑动时重复加载
    fun preloadImages(context: android.content.Context) {
        viewModelScope.launch {
            agentList.forEach { agent ->
                if (agent.id !in preloadedImageIds && agent.avatar.isNotEmpty()) {
                    try {
                        // 预加载头像图片到缓存
                        com.aiosman.ravenow.utils.Utils.getImageLoader(context).enqueue(
                            coil3.request.ImageRequest.Builder(context)
                                .data(agent.avatar)
                                .memoryCachePolicy(coil3.request.CachePolicy.ENABLED)
                                .diskCachePolicy(coil3.request.CachePolicy.ENABLED)
                                .build()
                        )
                        preloadedImageIds.add(agent.id)
                    } catch (e: Exception) {
                        // 忽略预加载错误
                    }
                }
            }
        }
    }
    
    // 清除预加载记录（在刷新时调用）
    fun clearPreloadedImages() {
        preloadedImageIds.clear()
    }
}