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.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 AiProfileViewModel : 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())

    init {
        EventBus.getDefault().register(this)
    }

    fun loadProfile(id: String, pullRefresh: Boolean = false) {
        viewModelScope.launch {
            if (pullRefresh) {
                refreshing = true
            }
            
            try {
                // 先通过用户ID获取基本信息，获取chatAIId
                val basicProfile = userService.getUserProfile(id)
                profileId = id.toInt()
                
                // 使用chatAIId通过getUserProfileByOpenId获取完整信息（包含creatorProfile）
                profile = userService.getUserProfileByOpenId(basicProfile.chatAIId)
            } catch (e: Exception) {
                Log.e("AiProfileViewModel", "Error loading profile", e)
                e.printStackTrace()
            }

            refreshing = false
            
            profile?.let {
                try {
                    momentLoader.loadData(MomentLoaderExtraArgs(authorId = it.id))
                } catch (e: Exception) {
                    Log.e("AiProfileViewModel", "Error loading moments", e)
                    e.printStackTrace()
                }
            }
        }
    }

    fun loadMoreMoment() {
        viewModelScope.launch {
            profile?.let { profileData ->
                try {
                    Log.d("AiProfileViewModel", "loadMoreMoment: 开始加载更多, 当前moments数量: ${moments.size}, hasNext: ${momentLoader.hasNext}")
                    momentLoader.loadMore(extra = MomentLoaderExtraArgs(authorId = profileData.id))
                    Log.d("AiProfileViewModel", "loadMoreMoment: 加载完成, 新的moments数量: ${moments.size}")
                } catch (e: Exception) {
                    Log.e("AiProfileViewModel", "loadMoreMoment: ", e)
                }
            } ?: Log.w("AiProfileViewModel", "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 {
            try {
                userService.followUser(userId)
                EventBus.getDefault().post(FollowChangeEvent(userId.toInt(), true))
            } catch (e: Exception) {
                Log.e("AiProfileViewModel", "Error following user", e)
            }
        }
    }

    fun unFollowUser(userId: String) {
        viewModelScope.launch {
            try {
                userService.unFollowUser(userId)
                EventBus.getDefault().post(FollowChangeEvent(userId.toInt(), false))
            } catch (e: Exception) {
                Log.e("AiProfileViewModel", "Error unfollowing user", e)
            }
        }
    }

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

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

