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
import android.util.Log
import com.aiosman.ravenow.data.Room
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.ConstVars
import com.aiosman.ravenow.data.api.CreateGroupChatRequestBody
import com.aiosman.ravenow.ui.index.tabs.message.tab.GroupChatListViewModel.createGroupChat
import com.aiosman.ravenow.ui.navigateToGroupChat
import com.aiosman.ravenow.data.api.ApiErrorResponse
import com.google.gson.Gson
import android.content.Context
import android.widget.Toast
import kotlinx.coroutines.launch
import com.aiosman.ravenow.data.api.JoinGroupChatRequestBody


/**
 * 缓存数据结构，用于存储每个分类的Agent列表
 */
data class AgentCacheData(
    val items: List<AgentItem>,
    val currentPage: Int,
    val hasMoreData: Boolean
)
data class ChatRoom(
    val id: Int,
    val name: String,
    val avatar: String = "",
    val banner: String = "",
    val memberCount: Int
)

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 chatRooms by mutableStateOf<List<ChatRoom>>(emptyList())
        private set

    var rooms by mutableStateOf<List<Room>>(emptyList())
        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

    var isJoiningRoom by mutableStateOf(false)
        private set

    private val pageSize = 20
    private var currentCategoryId: Int? = null
    
    // 缓存：使用分类ID作为key，null表示推荐列表
    private val agentCache = mutableMapOf<Int?, AgentCacheData>()

    init {
        loadAgentData()
        loadCategories()
        loadChatRooms()
    }

    private fun loadAgentData(categoryId: Int? = null, page: Int = 1, isLoadMore: Boolean = false, forceRefresh: Boolean = false) {
        viewModelScope.launch {
            // 如果不是强制刷新且不是加载更多，检查缓存
            if (!forceRefresh && !isLoadMore) {
                val cached = agentCache[categoryId]
                if (cached != null && cached.items.isNotEmpty()) {
                    // 使用缓存数据
                    agentItems = cached.items
                    currentPage = cached.currentPage
                    hasMoreData = cached.hasMoreData
                    currentCategoryId = categoryId
                    println("使用缓存数据，分类ID: $categoryId, 数据数量: ${cached.items.size}")
                    return@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),
                        random = 1
                    )
                } else {
                    // 获取推荐智能体，使用random=1
                    apiClient.getAgent(
                        page = page,
                        pageSize = pageSize,
                        withWorkflow = 1,
                        categoryIds = null,
                        random = 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
                    
                    // 更新缓存
                    agentCache[categoryId] = AgentCacheData(
                        items = agentItems,
                        currentPage = currentPage,
                        hasMoreData = hasMoreData
                    )
                    println("更新缓存，分类ID: $categoryId, 数据数量: ${agentItems.size}")
                    
                } else {
                    errorMessage = "获取Agent数据失败: ${response.code()}"
                }
            } catch (e: Exception) {
                errorMessage = "网络请求失败: ${e.message}"
            } finally {
                if (isLoadMore) {
                    isLoadingMore = false
                } else {
                    isLoading = false
                }
            }
        }
    }

    private fun loadChatRooms() {
        viewModelScope.launch {
            try {
                val response = apiClient.getRooms(
                    page = 1,
                    pageSize = 20,
                    isRecommended = 1,
                    random = "1"
                )
                if (response.isSuccessful) {
                    val allRooms = response.body()?.list ?: emptyList()
                    val targetCount = (allRooms.size / 2) * 2
                    rooms = allRooms.take(targetCount)

                    // 转换为ChatRoom格式用于兼容现有UI
                    chatRooms = rooms.map { room ->
                        ChatRoom(
                            id = room.id,
                            name = room.name,
                            avatar = room.avatar,
                            banner = ConstVars.BASE_SERVER + "/api/v1/outside/" + room.recommendBanner + "?token=${AppStore.token}",
                            memberCount = room.userCount
                        )
                    }
                } else {

                }
            } catch (e: Exception) {
                // 如果网络请求失败，使用默认数据

            }
        }
    }

    private fun loadCategories() {
        viewModelScope.launch {
            // 如果分类已经加载，不重复请求
            if (categories.isNotEmpty()) {
                println("使用已缓存的分类数据，数量: ${categories.size}")
                return@launch
            }
            
            try {
                // 获取完整的语言标记（如 "zh-CN"）
                val fullLangTag = com.aiosman.ravenow.utils.Utils.getPreferredLanguageTag()
                // 转换为后端支持的语言代码（仅支持 zh、cn、ja）
                val sysLang = convertToSupportedLangCode(fullLangTag)
                val response = apiClient.getCategories(
                    page = 1,
                    pageSize = 100,
                    isActive = true,
//                    withChildren = false,
//                    withParent = false,
//                    withCount = true,
//                    hideEmpty = true,
                    lang = sysLang
                )
                println("分类数据请求完成，响应成功: ${response.isSuccessful}, 原始语言标记: $fullLangTag, 转换后: $sysLang")
                if (response.isSuccessful) {
                    val categoryList = response.body()?.list ?: emptyList()
                    println("获取到 ${categoryList.size} 个分类")
                    // 使用转换后的语言代码获取翻译后的分类名称
                    categories = categoryList.map { category ->
                        CategoryItem.fromCategoryTemplate(category, sysLang)
                    }
                    println("成功处理并映射了 ${categories.size} 个分类")
                } else {
                    errorMessage = "获取分类数据失败: ${response.code()}"
                    println("获取分类数据失败: ${response.code()}")
                }
            } catch (e: Exception) {
                errorMessage = "获取分类数据失败: ${e.message}"
                println("获取分类数据异常: ${e.message}")
                e.printStackTrace()
            }
        }
    }

    /**
     * 将完整的语言标记转换为后端支持的语言代码
     * 后端仅支持: zh, cn, ja
     * 
     * @param langTag 完整的语言标记，如 "zh-CN", "zh-TW", "ja-JP", "en-US" 等
     * @return 后端支持的语言代码，默认返回 "zh"
     */
    private fun convertToSupportedLangCode(langTag: String): String {
        return when {
            langTag.startsWith("zh", ignoreCase = true) -> "zh"
            langTag.startsWith("ja", ignoreCase = true) -> "ja"
            // 如果是中文相关的其他标记，也返回 zh
            langTag.equals("cn", ignoreCase = true) -> "cn"
            // 默认返回中文
            else -> "zh"
        }
    }

    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() {
        // 清除当前分类的缓存
        agentCache.remove(currentCategoryId)
        loadAgentData(categoryId = currentCategoryId, forceRefresh = true)
    }
    
    /**
     * 检查数据是否为空，如果为空则重新加载
     */
    fun ensureDataLoaded() {
        if (agentItems.isEmpty() && !isLoading) {
            loadAgentData()
        }
    }

    /**
     * 加入房间
     */
    fun joinRoom(
        id: Int,
        name: String,
        avatar: String,
        context: Context,
        navController: NavHostController,
        onSuccess: () -> Unit,
        onError: (String) -> Unit
    ) {
        // 防止重复点击
        if (isJoiningRoom) return

        viewModelScope.launch {
            try {
                isJoiningRoom = true
                val response = apiClient.joinRoom(JoinGroupChatRequestBody(roomId = id))
                if (response.isSuccessful) {
                    // 打开房间
                    val openRoomResponse = apiClient.createGroupChatAi(
                        roomId = id
                    )

                    if (openRoomResponse.isSuccessful){
                        val respData = openRoomResponse.body()
                        respData?.let {
                            viewModelScope.launch {
                                try {
                                    // 群聊直接使用群ID进行导航
                                    navController.navigateToGroupChat(
                                        id = respData.data.trtcRoomId,
                                        name = name,
                                        avatar = avatar
                                    )
                                } catch (e: Exception) {
                                    onError("加入房间失败")
                                    e.printStackTrace()
                                }
                            }
                        }
                    }
                    onSuccess()

                } else {
                    // 处理错误响应
                    try {
                        val errorBody = response.errorBody()?.string()
                        if (errorBody != null) {
                            val gson = Gson()
                            val errorResponse = gson.fromJson(errorBody, ApiErrorResponse::class.java)

                            // 在主线程显示 Toast
                            Toast.makeText(context, errorResponse.error, Toast.LENGTH_LONG).show()
                            onError(errorResponse.error)
                        } else {
                            Toast.makeText(context, "加入房间失败", Toast.LENGTH_SHORT).show()
                            onError("加入房间失败")
                        }
                    } catch (parseException: Exception) {
                        // 如果解析错误响应失败，显示默认错误信息
                        Toast.makeText(context, "加入房间失败", Toast.LENGTH_SHORT).show()
                        onError("加入房间失败")
                    }
                }
            } catch (e: Exception) {
                Toast.makeText(context, "网络请求失败：${e.message}", Toast.LENGTH_SHORT).show()
                onError("网络请求失败：${e.message}")
            } finally {
                isJoiningRoom = false
            }
        }
    }

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

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