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

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 androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import com.aiosman.ravenow.data.Agent
import com.aiosman.ravenow.data.AgentService
import com.aiosman.ravenow.data.MomentService
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.entity.AgentPagingSource
import com.aiosman.ravenow.entity.AgentRemoteDataSource
import com.aiosman.ravenow.entity.AgentServiceImpl
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.entity.MomentPagingSource
import com.aiosman.ravenow.entity.MomentRemoteDataSource
import com.aiosman.ravenow.entity.MomentServiceImpl
import com.aiosman.ravenow.ui.index.tabs.message.MessageListViewModel.userService
import com.aiosman.ravenow.ui.navigateToChatAi
import com.aiosman.ravenow.ui.NavigationRoute
// OpenIM SDK 导入 - 会话分组功能在 OpenIM 中不支持，将直接跳转到聊天页面
import android.util.Log
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

object MineAgentViewModel : ViewModel() {
    private val agentService: AgentService = AgentServiceImpl()

    private val _agentList =
        MutableStateFlow<PagingData<AgentEntity>>(PagingData.empty())
    val agentList = _agentList.asStateFlow()

    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)
    var isFirstLoad by mutableStateOf(true)
    
    // 记录已预加载的图片ID，避免重复加载
    private val preloadedImageIds = mutableSetOf<Int>()
    
    private val pageSize = 20

    
    fun refreshPager() {
        if (!isFirstLoad) {
            return
        }
        isFirstLoad = false
        viewModelScope.launch {
            Pager(
                config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                pagingSourceFactory = {
                    AgentPagingSource(

                        AgentRemoteDataSource(agentService),
                        //trend = true
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _agentList.value = it
            }
        }
    }

    fun createGroup2ChatAi(
        trtcUserId: String,
        groupName: String,
        navController: NavHostController,
        id: Int
    ) {
        // TODO: OpenIM 不支持会话分组功能，直接跳转到聊天页面
        // OpenIM 不支持会话分组功能，直接跳转到聊天页面
        Log.d("MineAgentViewModel", "OpenIM 不支持会话分组，直接跳转到 AI 聊天页面")
        navController.navigateToChatAi(id.toString())
    }


    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
            }
        }
    }
    
    /**
     * 重置ViewModel状态，用于登出或切换账号时清理数据
     */
    fun ResetModel() {
        // 重置状态变量
        refreshing = false
        isLoading = false
        hasNext = true
        currentPage = 1
        error = null
        isFirstLoad = true
        
        // 清除预加载的图片ID
        preloadedImageIds.clear()
        
        // 清空PagingData
        _agentList.value = PagingData.empty()
    }

}