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

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.data.MomentService
import com.aiosman.ravenow.entity.MomentServiceImpl
import com.aiosman.ravenow.data.PostRecommendationData
import com.aiosman.ravenow.data.RecommendationItem
import com.aiosman.ravenow.data.RecommendationService
import com.aiosman.ravenow.data.RecommendationServiceImpl
import com.aiosman.ravenow.data.ServiceException
import com.aiosman.ravenow.entity.MomentEntity
import kotlinx.coroutines.launch

/**
 * 推荐界面统一数据模型
 */
sealed class RecommendationDisplayItem {
    data class Post(val moment: MomentEntity) : RecommendationDisplayItem()
    data class Prompt(
        val id: Long,
        val title: String,
        val desc: String,
        val avatar: String?,
        val openId: String
    ) : RecommendationDisplayItem()
}

object RecommendViewModel : ViewModel() {
    private val recommendationService: RecommendationService = RecommendationServiceImpl()
    private val momentService: MomentService = MomentServiceImpl()
    
    var recommendations by mutableStateOf<List<RecommendationDisplayItem>>(listOf())
        private set
    
    var isLoading by mutableStateOf(false)
        private set
    
    var error by mutableStateOf<String?>(null)
        private set
    
    var hasNext by mutableStateOf(true)
        private set
    
    private var currentPage = 1
    private val pageSize = 20
    private var isFirstLoad = true
    
    /**
     * 刷新推荐列表
     */
    fun refreshRecommendations() {
        if (!isFirstLoad) {
            return
        }
        if (isLoading) {
            return
        }
        
        isFirstLoad = false
        currentPage = 1
        recommendations = listOf()
        hasNext = true
        
        viewModelScope.launch {
            loadRecommendations()
        }
    }
    
    /**
     * 加载更多推荐
     */
    fun loadMore() {
        if (isFirstLoad) {
            refreshRecommendations()
            return
        }
        if (!hasNext || isLoading) {
            return
        }
        
        viewModelScope.launch {
            currentPage++
            loadRecommendations(append = true)
        }
    }
    
    private suspend fun loadRecommendations(append: Boolean = false) {
        isLoading = true
        error = null
        
        try {
            Log.d("RecommendViewModel", "开始加载推荐数据，append=$append, pageSize=$pageSize")
            val items = recommendationService.getRecommendations(
                count = pageSize,
                lang = null,
                promptReplaceTrans = null
            )
            
            Log.d("RecommendViewModel", "获取到推荐数据: ${items.size} 条")
            
            // 过滤掉 post_music 和 room 类型
            val filteredItems = items.filter { 
                it.type !in listOf("post_music", "room")
            }
            
            Log.d("RecommendViewModel", "过滤后数据: ${filteredItems.size} 条")
            
            val displayItems = filteredItems.mapNotNull { item ->
                try {
                    when (item.type) {
                        "post_normal", "post_video", "post_news" -> {
                            val postData = item.toPostData()
                            if (postData != null) {
                                RecommendationDisplayItem.Post(postData.toMomentItem())
                            } else {
                                Log.w("RecommendViewModel", "无法转换 post 数据，type=${item.type}, id=${item.id}")
                                null
                            }
                        }
                        "prompt" -> {
                            val promptData = item.toPromptData()
                            if (promptData != null) {
                                // 优先使用 aiUserProfile 的 aiRoleAvatarMediumDirectUrl
                                val avatarUrl = promptData.aiUserProfile?.aiRoleAvatarMediumDirectUrl
                                    ?: promptData.aiUserProfile?.aiRoleAvatarDirectUrl
                                    ?: promptData.avatarDirectUrl 
                                    ?: promptData.avatar?.let { "${com.aiosman.ravenow.data.api.ApiClient.BASE_SERVER}$it" }
                                RecommendationDisplayItem.Prompt(
                                    id = promptData.id,
                                    title = promptData.title,
                                    desc = promptData.desc,
                                    avatar = avatarUrl,
                                    openId = promptData.openId ?: ""
                                )
                            } else {
                                Log.w("RecommendViewModel", "无法转换 prompt 数据，id=${item.id}")
                                null
                            }
                        }
                        else -> {
                            Log.w("RecommendViewModel", "未知类型: ${item.type}, id=${item.id}")
                            null
                        }
                    }
                } catch (e: Exception) {
                    Log.e("RecommendViewModel", "转换推荐项失败，type=${item.type}, id=${item.id}", e)
                    null
                }
            }
            
            Log.d("RecommendViewModel", "成功转换数据: ${displayItems.size} 条")
            
            if (append) {
                recommendations = recommendations + displayItems
            } else {
                recommendations = displayItems
            }
            
            hasNext = items.size >= pageSize
            Log.d("RecommendViewModel", "加载完成，当前总数: ${recommendations.size}, hasNext=$hasNext")
            
        } catch (e: ServiceException) {
            val errorMsg = e.message ?: "加载推荐失败"
            error = errorMsg
            Log.e("RecommendViewModel", "ServiceException: $errorMsg", e)
            e.printStackTrace()
            if (!append) {
                isFirstLoad = true // 允许重试
            }
        } catch (e: Exception) {
            val errorMsg = e.message ?: "加载推荐时发生未知错误"
            error = errorMsg
            Log.e("RecommendViewModel", "Exception: $errorMsg", e)
            e.printStackTrace()
            if (!append) {
                isFirstLoad = true // 允许重试
            }
        } finally {
            isLoading = false
        }
    }
    
    /**
     * 点赞动态
     */
    suspend fun likeMoment(id: Int) {
        try {
            momentService.likeMoment(id)
            updateMomentLike(id, true)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    /**
     * 取消点赞动态
     */
    suspend fun dislikeMoment(id: Int) {
        try {
            momentService.dislikeMoment(id)
            updateMomentLike(id, false)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    /**
     * 收藏动态
     */
    suspend fun favoriteMoment(id: Int) {
        try {
            momentService.favoriteMoment(id)
            updateMomentFavorite(id, true)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    /**
     * 取消收藏动态
     */
    suspend fun unfavoriteMoment(id: Int) {
        try {
            momentService.unfavoriteMoment(id)
            updateMomentFavorite(id, false)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    /**
     * 添加评论
     */
    fun onAddComment(id: Int) {
        updateMomentCommentCount(id, 1)
    }
    
    /**
     * 更新动态点赞状态
     */
    private fun updateMomentLike(id: Int, isLike: Boolean) {
        recommendations = recommendations.map { item ->
            if (item is RecommendationDisplayItem.Post && item.moment.id == id) {
                val moment = item.moment
                RecommendationDisplayItem.Post(
                    moment.copy(
                        liked = isLike,
                        likeCount = moment.likeCount + if (isLike) 1 else -1
                    )
                )
            } else {
                item
            }
        }
    }
    
    /**
     * 更新动态收藏状态
     */
    private fun updateMomentFavorite(id: Int, isFavorite: Boolean) {
        recommendations = recommendations.map { item ->
            if (item is RecommendationDisplayItem.Post && item.moment.id == id) {
                val moment = item.moment
                RecommendationDisplayItem.Post(
                    moment.copy(
                        isFavorite = isFavorite,
                        favoriteCount = moment.favoriteCount + if (isFavorite) 1 else -1
                    )
                )
            } else {
                item
            }
        }
    }
    
    /**
     * 更新动态评论数
     */
    private fun updateMomentCommentCount(id: Int, delta: Int) {
        recommendations = recommendations.map { item ->
            if (item is RecommendationDisplayItem.Post && item.moment.id == id) {
                val moment = item.moment
                RecommendationDisplayItem.Post(
                    moment.copy(
                        commentCount = (moment.commentCount + delta).coerceAtLeast(0)
                    )
                )
            } else {
                item
            }
        }
    }
    
    /**
     * 重置状态
     */
    fun reset() {
        recommendations = listOf()
        isLoading = false
        error = null
        hasNext = true
        currentPage = 1
        isFirstLoad = true
    }
}

