package com.aiosman.ravenow.ui.index.tabs.profile

import android.content.Context
import android.net.Uri
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.AppState
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.Messaging
import com.aiosman.ravenow.data.AccountService
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.MomentService
import com.aiosman.ravenow.data.UploadImage
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.entity.MomentServiceImpl
import com.aiosman.ravenow.event.FollowChangeEvent
import com.aiosman.ravenow.event.MomentAddEvent
import com.aiosman.ravenow.event.MomentFavouriteChangeEvent
import com.aiosman.ravenow.event.MomentLikeChangeEvent
import com.aiosman.ravenow.event.MomentRemoveEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.io.File

object MyProfileViewModel : ViewModel() {
    val accountService: AccountService = AccountServiceImpl()
    val momentService: MomentService = MomentServiceImpl()
    var profile by mutableStateOf<AccountProfileEntity?>(null)
    var moments by mutableStateOf<List<MomentEntity>>(emptyList())
    var agents by mutableStateOf<List<AgentEntity>>(emptyList())
    val momentLoader: MomentLoader = MomentLoader().apply {
        pageSize = 20  // 设置与后端一致的页面大小
        onListChanged = {
            moments = it
        }
    }
    val agentLoader: AgentLoader = AgentLoader().apply {
        onListChanged = {
            agents = it
        }
    }
    var refreshing by mutableStateOf(false)
    var firstLoad = true

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

    suspend fun loadUserProfile() {
        // 游客模式下不获取用户资料
        if (AppStore.isGuest) {
            MyProfileViewModel.profile = null
            return
        }
        
        val profile = accountService.getMyAccountProfile()
        MyProfileViewModel.profile = profile
    }

    fun loadProfile(pullRefresh: Boolean = false) {
        if (!firstLoad && !pullRefresh) return
        viewModelScope.launch {
            if (pullRefresh) {
                refreshing = true
            }
            firstLoad = false
            loadUserProfile()
            refreshing = false
            
            // 游客模式下不加载个人动态和智能体
            if (AppStore.isGuest) {
                return@launch
            }
            
            profile?.let {
                try {
                    momentLoader.loadData(extra = MomentLoaderExtraArgs(authorId = it.id))
                    // MyProfileViewModel 总是加载当前用户的数据，所以传递null以调用getMyAgent()
                    agentLoader.loadData(extra = AgentLoaderExtraArgs(authorId = null))
                } catch (e: Exception) {
                    Log.e("MyProfileViewModel", "loadProfile: ", e)
                }
            }

        }
    }

    fun loadMoreMoment() {
        // 游客模式下不加载更多动态
        if (AppStore.isGuest) {
            Log.d("MyProfileViewModel", "loadMoreMoment: 游客模式下跳过加载更多动态")
            return
        }
        
        viewModelScope.launch {
            profile?.let { profileData ->
                try {
                    Log.d("MyProfileViewModel", "loadMoreMoment: 开始加载更多, 当前moments数量: ${moments.size}, hasNext: ${momentLoader.hasNext}")
                    momentLoader.loadMore(extra = MomentLoaderExtraArgs(authorId = profileData.id))
                    Log.d("MyProfileViewModel", "loadMoreMoment: 加载完成, 新的moments数量: ${moments.size}")
                } catch (e: Exception) {
                    Log.e("MyProfileViewModel", "loadMoreMoment: ", e)
                }
            } ?: Log.w("MyProfileViewModel", "loadMoreMoment: profile为null，无法加载更多")
        }
    }

    fun logout(context: Context) {
        viewModelScope.launch {
            // 只有非游客用户才需要取消注册推送设备
            if (!AppStore.isGuest) {
                Messaging.unregisterDevice(context)
            }
            
            AppStore.apply {
                token = null
                rememberMe = false
                isGuest = false  // 清除游客状态
                saveData()
            }
            // 删除推送渠道和重置应用状态
            AppState.ReloadAppState(context)
        }

    }

    fun updateUserProfileBanner(bannerImageUrl: Uri?, file: File, context: Context) {
        // 游客模式下不允许更新用户资料
        if (AppStore.isGuest) {
            Log.d("MyProfileViewModel", "updateUserProfileBanner: 游客模式下无法更新用户资料")
            return
        }
        
        viewModelScope.launch {
            val newBanner = bannerImageUrl?.let {
                val cursor = context.contentResolver.query(it, null, null, null, null)
                var newBanner: UploadImage? = null
                cursor?.use { cur ->
                    val columnIndex = cur.getColumnIndex("_display_name")
                    if (cur.moveToFirst() && columnIndex != -1) {
                        val displayName = cur.getString(columnIndex)
                        val extension = displayName.substringAfterLast(".")
                        Log.d("Change banner", "File name: $displayName, extension: $extension")
                        // read as file
                        Log.d("Change banner", "File size: ${file.length()}")
                        newBanner = UploadImage(file, displayName, it.toString(), extension)
                    }
                }
                newBanner
            }
            accountService.updateProfile(
                banner = newBanner,
                avatar = null,
                nickName = null,
                bio = null
            )
            profile = accountService.getMyAccountProfile()
        }
    }

    fun likeMoment(momentLMomentEntity: MomentEntity) {
        // 游客模式下不允许点赞
        if (AppStore.isGuest) {
            Log.d("MyProfileViewModel", "likeMoment: 游客模式下无法点赞")
            return
        }
        
        viewModelScope.launch {
            if (momentLMomentEntity.liked) {
                momentService.dislikeMoment(momentLMomentEntity.id)
                EventBus.getDefault().post(
                    MomentLikeChangeEvent(
                        momentLMomentEntity.id,
                        likeCount = momentLMomentEntity.likeCount - 1,
                        isLike = false
                    )
                )
            } else {
                momentService.likeMoment(momentLMomentEntity.id)
                EventBus.getDefault().post(
                    MomentLikeChangeEvent(
                        momentLMomentEntity.id,
                        likeCount = momentLMomentEntity.likeCount + 1,
                        isLike = true
                    )
                )
            }
        }
    }


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

    fun ResetModel() {
        profile = null
        momentLoader.clear()
        agentLoader.clear()
        firstLoad = true
    }

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

    @Subscribe
    fun onMomentLikeChangeEvent(event: MomentLikeChangeEvent) {
        momentLoader.updateMomentLike(event.postId, event.isLike)
    }

    @Subscribe
    fun onMomentFavoriteChangeEvent(event: MomentFavouriteChangeEvent) {
        momentLoader.updateFavoriteCount(event.postId, event.isFavourite)
    }

    @Subscribe
    fun onRemoveMomentEvent(event: MomentRemoveEvent) {
        momentLoader.removeMoment(event.postId)
    }

    @Subscribe
    fun onAddMomentEvent(event: MomentAddEvent) {
        momentLoader.addMoment(event.moment)
    }

    @Subscribe
    fun onMomentDelete(event: MomentRemoveEvent) {
        momentLoader.removeMoment(event.postId)
    }

    @Subscribe
    fun onFollowChangeEvent(event: FollowChangeEvent) {
        momentLoader.updateFollowStatus(event.userId, event.isFollow)
    }
}