package com.aiosman.riderpro.ui.index.tabs.moment

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.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.filter
import androidx.paging.map
import com.aiosman.riderpro.AppState
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.entity.MomentPagingSource
import com.aiosman.riderpro.entity.MomentRemoteDataSource
import com.aiosman.riderpro.data.MomentService
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.entity.MomentServiceImpl
import com.aiosman.riderpro.entity.MomentEntity
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch


object MomentViewModel : ViewModel() {
    private val momentService: MomentService = MomentServiceImpl()
    private val _momentsFlow = MutableStateFlow<PagingData<MomentEntity>>(PagingData.empty())
    val momentsFlow = _momentsFlow.asStateFlow()
    val accountService: AccountService = AccountServiceImpl()
    var existsMoment = mutableStateOf(false)
    var refreshing by mutableStateOf(false)
    init {
        refreshPager()
    }

    fun refreshPager(pullRefresh: Boolean = false) {
        viewModelScope.launch {
            if (pullRefresh) {
                refreshing = true
            }
            // 检查是否有动态
            val existMoments = momentService.getMoments(timelineId = AppState.UserId, pageNumber = 1)
            if (existMoments.list.isEmpty()) {
                existsMoment.value = true
            }
            if (pullRefresh) {
                refreshing = false
            }
            Pager(
                config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                pagingSourceFactory = {
                    MomentPagingSource(
                        MomentRemoteDataSource(momentService),
                        // 如果没有动态，则显示热门动态
                        timelineId = if (existMoments.list.isEmpty()) null else AppState.UserId,
                        trend = if (existMoments.list.isEmpty()) true else null
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _momentsFlow.value = it
            }
        }
    }

    fun updateLikeCount(id: Int) {
        val currentPagingData = _momentsFlow.value
        val updatedPagingData = currentPagingData.map { momentItem ->
            if (momentItem.id == id) {
                momentItem.copy(likeCount = momentItem.likeCount + 1, liked = true)
            } else {
                momentItem
            }
        }
        _momentsFlow.value = updatedPagingData
    }

    suspend fun likeMoment(id: Int) {
        momentService.likeMoment(id)
        updateLikeCount(id)
    }

    fun updateCommentCount(id: Int) {
        val currentPagingData = _momentsFlow.value
        val updatedPagingData = currentPagingData.map { momentItem ->
            if (momentItem.id == id) {
                momentItem.copy(commentCount = momentItem.commentCount + 1)
            } else {
                momentItem
            }
        }
        _momentsFlow.value = updatedPagingData
    }

    suspend fun onAddComment(id: Int) {
        val currentPagingData = _momentsFlow.value
        updateCommentCount(id)
    }


    fun updateDislikeMomentById(id: Int) {
        val currentPagingData = _momentsFlow.value
        val updatedPagingData = currentPagingData.map { momentItem ->
            if (momentItem.id == id) {
                momentItem.copy(likeCount = momentItem.likeCount - 1, liked = false)
            } else {
                momentItem
            }
        }
        _momentsFlow.value = updatedPagingData
    }

    suspend fun dislikeMoment(id: Int) {
        momentService.dislikeMoment(id)
        updateDislikeMomentById(id)
    }

    fun updateFavoriteCount(id: Int) {
        val currentPagingData = _momentsFlow.value
        val updatedPagingData = currentPagingData.map { momentItem ->
            if (momentItem.id == id) {
                momentItem.copy(favoriteCount = momentItem.favoriteCount + 1, isFavorite = true)
            } else {
                momentItem
            }
        }
        _momentsFlow.value = updatedPagingData
    }

    suspend fun favoriteMoment(id: Int) {
        momentService.favoriteMoment(id)
        updateFavoriteCount(id)
    }

    fun updateUnfavoriteCount(id: Int) {
        val currentPagingData = _momentsFlow.value
        val updatedPagingData = currentPagingData.map { momentItem ->
            if (momentItem.id == id) {
                momentItem.copy(favoriteCount = momentItem.favoriteCount - 1, isFavorite = false)
            } else {
                momentItem
            }
        }
        _momentsFlow.value = updatedPagingData
    }

    suspend fun unfavoriteMoment(id: Int) {
        momentService.unfavoriteMoment(id)
        updateUnfavoriteCount(id)
    }

    fun deleteMoment(id: Int) {
        val currentPagingData = _momentsFlow.value
        val updatedPagingData = currentPagingData.filter { momentItem ->
            momentItem.id != id
        }
        _momentsFlow.value = updatedPagingData
    }

    /**
     * 更新动态评论数
     */
    fun updateMomentCommentCount(id: Int,delta: Int) {
        val currentPagingData = _momentsFlow.value
        val updatedPagingData = currentPagingData.map { momentItem ->
            if (momentItem.id == id) {
                momentItem.copy(commentCount = momentItem.commentCount + delta)
            } else {
                momentItem
            }
        }
        _momentsFlow.value = updatedPagingData
    }
}