package com.aiosman.ravenow.ui.profile

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.AccountService
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.entity.AccountProfileEntity
import com.aiosman.ravenow.entity.AgentEntity
import com.aiosman.ravenow.entity.AgentLoader
import com.aiosman.ravenow.entity.AgentLoaderExtraArgs
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.entity.MomentLoader
import com.aiosman.ravenow.entity.MomentLoaderExtraArgs
import com.aiosman.ravenow.event.FollowChangeEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe


class AccountProfileViewModel : ViewModel() {
    var profileId by mutableStateOf(0)
    val accountService: AccountService = AccountServiceImpl()
    val userService = UserServiceImpl()
    var profile by mutableStateOf<AccountProfileEntity?>(null)
    var refreshing by mutableStateOf(false)
    var momentLoader = MomentLoader().apply {
        pageSize = 20  // 设置与后端一致的页面大小
        onListChanged = {
            moments = it
        }
    }
    var moments by mutableStateOf<List<MomentEntity>>(listOf())
    
    var agentLoader = AgentLoader().apply {
        onListChanged = {
            agents = it
        }
    }
    var agents by mutableStateOf<List<AgentEntity>>(listOf())
    init {
        EventBus.getDefault().register(this)
    }

    fun loadProfile(id: String, pullRefresh: Boolean = false) {
        viewModelScope.launch {
            if (pullRefresh) {
                refreshing = true
            }
            if (profileId == profile?.id) {
                return@launch
            }
            try {
                profile = userService.getUserProfile(id)
            } catch (e: Exception) {
                e.printStackTrace()
            }

            refreshing = false
            profile?.let {
                try {
                    momentLoader.loadData(MomentLoaderExtraArgs(authorId = it.id))
                    // 根据是否是当前用户来决定传递authorId
                    // 如果是当前用户，传递null以调用getMyAgent()
                    // 如果是其他用户，传递用户ID以调用getAgent(authorId)
                    val isSelf = it.id.toString() == com.aiosman.ravenow.AppState.UserId.toString()
                    val authorId = if (isSelf) null else it.id
                    agentLoader.loadData(AgentLoaderExtraArgs(authorId = authorId))
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    fun loadMoreMoment() {
        viewModelScope.launch {
            profile?.let { profileData ->
                try {
                    Log.d("AccountProfileViewModel", "loadMoreMoment: 开始加载更多, 当前moments数量: ${moments.size}, hasNext: ${momentLoader.hasNext}")
                    momentLoader.loadMore(extra = MomentLoaderExtraArgs(authorId = profileData.id))
                    Log.d("AccountProfileViewModel", "loadMoreMoment: 加载完成, 新的moments数量: ${moments.size}")
                } catch (e: Exception) {
                    Log.e("AccountProfileViewModel", "loadMoreMoment: ", e)
                }
            } ?: Log.w("AccountProfileViewModel", "loadMoreMoment: profile为null，无法加载更多")
        }
    }

    @Subscribe
    fun onFollowChangeEvent(event: FollowChangeEvent) {
        if (event.userId == profile?.id) {
            profile = profile?.copy(followerCount = profile!!.followerCount + if (event.isFollow) 1 else -1, isFollowing = event.isFollow)
        }
    }
    fun followUser(userId: String) {
        viewModelScope.launch {
            userService.followUser(userId)
            EventBus.getDefault().post(FollowChangeEvent(userId.toInt(), true))
        }
    }

    fun unFollowUser(userId: String) {
        viewModelScope.launch {
            userService.unFollowUser(userId)
            EventBus.getDefault().post(FollowChangeEvent(userId.toInt(), false))
        }
    }

    val bio get() = profile?.bio ?: ""
    val nickName get() = profile?.nickName ?: ""
    val avatar get() = profile?.avatar

    override fun onCleared() {
        super.onCleared()
        EventBus.getDefault().unregister(this)
    }

}