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

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.Agent
import com.aiosman.ravenow.data.ListContainer
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.data.api.CategoryTemplate
import com.aiosman.ravenow.data.api.RaveNowAPI
import com.aiosman.ravenow.data.api.SingleChatRequestBody
import com.aiosman.ravenow.ui.index.tabs.ai.tabs.mine.MineAgentViewModel.createGroup2ChatAi
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.index.tabs.message.MessageListViewModel.userService
import com.aiosman.ravenow.ui.index.tabs.moment.tabs.expolre.AgentItem
import kotlinx.coroutines.launch

object AgentViewModel: ViewModel() {

    private val apiClient: RaveNowAPI = ApiClient.api

    var agentItems by mutableStateOf<List<AgentItem>>(emptyList())
        private set

    var categories by mutableStateOf<List<CategoryItem>>(emptyList())
        private set

    var errorMessage by mutableStateOf<String?>(null)
        private set


    var isRefreshing by mutableStateOf(false)
        private set

    var isLoading 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
    
    private val pageSize = 20
    private var currentCategoryId: Int? = null

    init {
        loadAgentData()
        loadCategories()
    }

    private fun loadAgentData(categoryId: Int? = null, page: Int = 1, isLoadMore: Boolean = false) {
        viewModelScope.launch {
            if (isLoadMore) {
                isLoadingMore = true
            } else {
                isLoading = true
                // 重置分页状态
                currentPage = 1
                hasMoreData = true
                currentCategoryId = categoryId
            }
            
            errorMessage = null
            try {
                val response = if (categoryId != null) {
                    // 根据分类ID获取智能体
                    apiClient.getAgent(
                        page = page,
                        pageSize = pageSize,
                        withWorkflow = 1,
                        categoryIds = listOf(categoryId)
                    )
                } else {
                    // 获取所有智能体
                    apiClient.getAgent(page = page, pageSize = pageSize, withWorkflow = 1)
                }

                if (response.isSuccessful) {
                    val responseData = response.body()?.data
                    val agents = responseData?.list ?: emptyList<Agent>()
                    val newAgentItems = agents.map { agent ->
                        AgentItem.fromAgent(agent)
                    }

                    if (isLoadMore) {
                        // 加载更多：追加到现有列表
                        agentItems = agentItems + newAgentItems
                        currentPage = page
                    } else {
                        // 首次加载或刷新：替换整个列表
                        agentItems = newAgentItems
                        currentPage = 1
                    }
                    
                    // 检查是否还有更多数据
                    hasMoreData = agents.size >= pageSize
                    
                } else {
                    errorMessage = "获取Agent数据失败: ${response.code()}"
                }
            } catch (e: Exception) {
                errorMessage = "网络请求失败: ${e.message}"
            } finally {
                if (isLoadMore) {
                    isLoadingMore = false
                } else {
                    isLoading = false
                }
            }
        }
    }

    private fun loadCategories() {
        viewModelScope.launch {
            try {
                val response = apiClient.getCategories(
                    pageSize = 20,
                    withChildren = false,
                    withParent = false,
                    withCount = true,
                    hideEmpty = true
                )
                println("分类数据请求完成，响应成功: ${response.isSuccessful}")
                if (response.isSuccessful) {
                    val categoryList = response.body()?.data?.list ?: emptyList()
                    println("获取到 ${categoryList.size} 个分类")
                    categories = categoryList.map { category ->
                        CategoryItem.fromCategoryTemplate(category)
                    }
                    println("成功处理并映射了 ${categories.size} 个分类")
                } else {
                    errorMessage = "获取分类数据失败: ${response.code()}"
                    println("获取分类数据失败: ${response.code()}")
                }
            } catch (e: Exception) {
                errorMessage = "获取分类数据失败: ${e.message}"
                println("获取分类数据异常: ${e.message}")
                e.printStackTrace()
            }
        }
    }

    fun loadAgentsByCategory(categoryId: Int) {
        loadAgentData(categoryId)
    }

    fun loadAllAgents() {
        loadAgentData()
    }

    /**
     * 加载更多Agent数据
     */
    fun loadMoreAgents() {
        // 检查是否正在加载或没有更多数据
        if (isLoadingMore || !hasMoreData) {
            return
        }
        
        val nextPage = currentPage + 1
        loadAgentData(
            categoryId = currentCategoryId,
            page = nextPage,
            isLoadMore = true
        )
    }
    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
            }
        }
    }

    /**
     * 刷新推荐Agent数据
     */
    fun refreshAgentData() {
        loadAgentData()
    }
    
    /**
     * 检查数据是否为空，如果为空则重新加载
     */
    fun ensureDataLoaded() {
        if (agentItems.isEmpty() && !isLoading) {
            loadAgentData()
        }
    }

    /**
     * 重置ViewModel状态，用于登出或切换账号时清理数据
     */
    fun ResetModel() {
        agentItems = emptyList()
        errorMessage = null
        isRefreshing = false
        isLoading = false
        isLoadingMore = false
        currentPage = 1
        hasMoreData = true
        currentCategoryId = null
    }

}
data class CategoryItem(
    val id: Int,
    val name: String,
    val description: String,
    val avatar: String,
    val promptCount: Int?
) {
    companion object {
        fun fromCategoryTemplate(template: CategoryTemplate): CategoryItem {
            return CategoryItem(
                id = template.id,
                name = template.name,
                description = template.description,
                avatar = "${ApiClient.BASE_API_URL}${template.avatar}",
                promptCount = template.promptCount
            )
        }
    }
}
