package com.aiosman.ravenow.ui.index.tabs.moment.tabs.expolre

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.Room
import com.aiosman.ravenow.data.Agent
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.data.api.RaveNowAPI
import com.aiosman.ravenow.data.api.SingleChatRequestBody
import com.aiosman.ravenow.data.api.JoinGroupChatRequestBody
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.index.tabs.message.tab.GroupChatListViewModel
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

class ExploreViewModel : ViewModel() {

    private val apiClient: RaveNowAPI = ApiClient.api

    var bannerItems by mutableStateOf<List<BannerItem>>(emptyList())
        private set

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

    var isLoading by mutableStateOf(false)
        private set

    var isRefreshing by mutableStateOf(false)
        private set

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

    init {
        loadBannerData()
        loadAgentData()
    }

    fun refreshBannerData() {
        viewModelScope.launch {
            isRefreshing = true
            errorMessage = null
            try {
                val response = apiClient.getRooms(page = 1, pageSize = 12, isRecommended = 1)
                if (response.isSuccessful) {
                    val rooms = response.body()?.list ?: emptyList()
                    bannerItems = rooms.map { room ->
                        BannerItem.fromRoom(room)
                    }
                } else {
                    errorMessage = "获取数据失败: ${response.code()}"
                }
            } catch (e: Exception) {
                errorMessage = "网络请求失败: ${e.message}"
            } finally {
                isRefreshing = false
            }
        }
    }

    fun refreshAgentData() {
        viewModelScope.launch {
            isRefreshing = true
            errorMessage = null
            try {
                val response = apiClient.getAgent(page = 1, pageSize = 20, withWorkflow = 1)
                if (response.isSuccessful) {
                    val agents = response.body()?.data?.list ?: emptyList()
                    agentItems = agents.map { agent ->
                        AgentItem.fromAgent(agent)
                    }
                } else {
                    errorMessage = "获取Agent数据失败: ${response.code()}"
                }
            } catch (e: Exception) {
                errorMessage = "网络请求失败: ${e.message}"
            } finally {
                isRefreshing = false
            }
        }
    }

    private fun loadBannerData() {
        viewModelScope.launch {
            isLoading = true
            errorMessage = null
            try {
                val response = apiClient.getRooms(page = 1, pageSize = 10, isRecommended = 1)
                if (response.isSuccessful) {
                    val rooms = response.body()?.list ?: emptyList()
                    bannerItems = rooms.map { room ->
                        BannerItem.fromRoom(room)
                    }
                } else {
                    errorMessage = "获取数据失败: ${response.code()}"
                }
            } catch (e: Exception) {
                errorMessage = "网络请求失败: ${e.message}"
            } finally {
                isLoading = false
            }
        }
    }

    private fun loadAgentData() {
        viewModelScope.launch {
            isLoading = true
            errorMessage = null
            try {
                val response = apiClient.getAgent(page = 1, pageSize = 20, withWorkflow = 1)
                if (response.isSuccessful) {
                    val agents = response.body()?.data?.list ?: emptyList()
                    agentItems = agents.map { agent ->
                        AgentItem.fromAgent(agent)
                    }
                } else {
                    errorMessage = "获取Agent数据失败: ${response.code()}"
                }
            } catch (e: Exception) {
                errorMessage = "网络请求失败: ${e.message}"
            } 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 joinRoom(
        trtcId: String,
        name: String,
        avatar: String,
        context: Context,
        navController: NavHostController,
        onSuccess: () -> Unit,
        onError: (String) -> Unit
    ) {
        viewModelScope.launch {
            try {
                val response = apiClient.joinRoom(JoinGroupChatRequestBody(trtcId = trtcId))
                if (response.isSuccessful) {
                    viewModelScope.launch {
                        try {
                            createGroupChat(trtcGroupId = trtcId)
                            // 群聊直接使用群ID进行导航
                            navController.navigateToGroupChat(
                                id = trtcId,
                                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}")
            }
        }
    }

}