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.entity.RoomEntity
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.data.api.RaveNowAPI
import com.aiosman.ravenow.data.Room
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 com.aiosman.ravenow.data.PointService
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
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())
    var rooms by mutableStateOf<List<RoomEntity>>(emptyList())
    var roomsLoading by mutableStateOf(false)
    var roomsRefreshing by mutableStateOf(false)
    var roomsCurrentPage by mutableStateOf(1)
    var roomsHasMore by mutableStateOf(true)
    private val roomsPageSize = 20
    private val apiClient: RaveNowAPI = ApiClient.api
    
    var profileScrollOffset by mutableStateOf(0)
    var profileGridFirstVisibleItemIndex by mutableStateOf(0)
    var profileGridFirstVisibleItemOffset by mutableStateOf(0)
    var profileAgentListFirstVisibleItemIndex by mutableStateOf(0)
    var profileAgentListFirstVisibleItemOffset by mutableStateOf(0)
    var profileGroupChatFirstVisibleItemIndex by mutableStateOf(0)
    var profileGroupChatFirstVisibleItemOffset by mutableStateOf(0)
    var profileCurrentPage by mutableStateOf(0)
    
    val momentLoader: MomentLoader = MomentLoader().apply {
        pageSize = 20  // 设置与后端一致的页面大小
        onListChanged = { updated ->
            moments = updated.toList()
        }
    }
    val agentLoader: AgentLoader = AgentLoader().apply {
        onListChanged = { updated ->
            agents = updated.toList()
        }
    }
    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()
            // 刷新积分（仅非游客）
            if (!AppStore.isGuest) {
                try {
                    PointService.refreshMyPointsBalance()
                } catch (e: Exception) {
                    Log.e("MyProfileViewModel", "refresh points error: ", e)
                }
            }
            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 loadMoreAgent() {
        if (AppStore.isGuest) {
            Log.d("MyProfileViewModel", "loadMoreAgent: 游客模式下跳过加载更多智能体")
            return
        }

        viewModelScope.launch {
            try {
                Log.d("MyProfileViewModel", "loadMoreAgent: hasNext = ${agentLoader.hasNext}")
                if (profile == null) {
                    agentLoader.loadMore(extra = AgentLoaderExtraArgs(authorId = null))
                } else {
                    agentLoader.loadMore(extra = AgentLoaderExtraArgs(authorId = profile?.id))
                }
            } catch (e: Exception) {
                Log.e("MyProfileViewModel", "loadMoreAgent: ", e)
            }
        }
    }

    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
        profileScrollOffset = 0
        profileGridFirstVisibleItemIndex = 0
        profileGridFirstVisibleItemOffset = 0
        profileAgentListFirstVisibleItemIndex = 0
        profileAgentListFirstVisibleItemOffset = 0
        profileGroupChatFirstVisibleItemIndex = 0
        profileGroupChatFirstVisibleItemOffset = 0
        profileCurrentPage = 0
    }

    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)
    }

    /**
     * 加载房间列表
     * @param filterType 筛选类型：0=全部，1=公开，2=私有
     * @param pullRefresh 是否下拉刷新
     * @param ownerSessionId 创建者用户ID（ChatAIID），用于过滤特定创建者的房间。如果为null，则显示当前用户创建或加入的房间
     */
    fun loadRooms(filterType: Int = 0, pullRefresh: Boolean = false, ownerSessionId: String? = null) {
        // 游客模式下不加载房间列表
        if (AppStore.isGuest) {
            Log.d("MyProfileViewModel", "loadRooms: 游客模式下跳过加载房间列表")
            return
        }
        
        if (roomsLoading && !pullRefresh) return
        
        viewModelScope.launch {
            try {
                roomsLoading = true
                roomsRefreshing = pullRefresh
                
                val currentPage = if (pullRefresh) {
                    roomsCurrentPage = 1
                    roomsHasMore = true
                    1
                } else {
                    roomsCurrentPage
                }
                
                // 根据filterType确定roomType
                val roomType = when (filterType) {
                    1 -> "public"
                    2 -> "private"
                    else -> null
                }
                
                // 构建API调用参数
                if (ownerSessionId != null) {
                    // 查看其他用户的房间：显示该用户创建和加入的房间
                    // 1. 先快速获取该用户创建的房间（不需要 includeUsers，减少数据量）
                    val createdResponse = apiClient.getRooms(
                        page = currentPage,
                        pageSize = roomsPageSize,
                        roomType = roomType,
                        ownerSessionId = ownerSessionId,
                        includeUsers = false
                    )
                    
                    val createdRooms = if (createdResponse.isSuccessful) {
                        createdResponse.body()?.list?.map { it.toRoomtEntity() } ?: emptyList()
                    } else {
                        emptyList()
                    }
                    
                    // 先快速显示创建的房间，提升用户体验
                    if (pullRefresh || currentPage == 1) {
                        rooms = createdRooms
                    } else {
                        rooms = rooms + createdRooms
                    }
                    
                    // 处理分页（基于创建的房间）
                    val total = createdResponse.body()?.total ?: 0L
                    roomsHasMore = rooms.size < total
                    if (roomsHasMore && !pullRefresh) {
                        roomsCurrentPage++
                    }
                    
                    // 2. 后台异步获取该用户加入的房间（仅在非私有房间时获取，且只在第一页时获取以提升性能）
                    if (filterType != 2 && currentPage == 1) {
                        launch {
                            try {
                                // 获取公开房间，但限制数量以减少数据量
                                val joinedResponse = apiClient.getRooms(
                                    page = 1,
                                    pageSize = roomsPageSize,
                                    roomType = if (filterType == 1) "public" else null,
                                    includeUsers = true // 需要成员信息来判断
                                )
                                
                                if (joinedResponse.isSuccessful) {
                                    val joinedRooms = joinedResponse.body()?.list?.mapNotNull { room ->
                                        try {
                                            val entity = room.toRoomtEntity()
                                            // 检查房间的创建者是否是该用户
                                            val isCreatedByUser = entity.creator.profile.chatAIId == ownerSessionId
                                            // 检查房间的成员是否包含该用户
                                            val isMember = entity.users.any { it.profile.chatAIId == ownerSessionId }
                                            
                                            // 如果用户是成员但不是创建者，则认为是加入的房间
                                            if (isMember && !isCreatedByUser) {
                                                entity
                                            } else {
                                                null
                                            }
                                        } catch (e: Exception) {
                                            Log.e("MyProfileViewModel", "处理房间失败: ${e.message}")
                                            null
                                        }
                                    } ?: emptyList()
                                    
                                    // 合并并去重（基于房间ID），然后更新列表
                                    val allRooms = (rooms + joinedRooms).distinctBy { it.id }
                                    rooms = allRooms
                                }
                            } catch (e: Exception) {
                                Log.e("MyProfileViewModel", "获取加入的房间失败: ${e.message}")
                            }
                        }
                    }
                } else {
                    // 查看自己的房间：显示创建或加入的房间
                    val response = apiClient.getRooms(
                        page = currentPage,
                        pageSize = roomsPageSize,
                        roomType = roomType,
                        showCreated = true,
                        showJoined = if (filterType == 2) null else true // 私有房间不显示加入的
                    )
                    
                    if (response.isSuccessful) {
                        val roomList = response.body()?.list ?: emptyList()
                        val total = response.body()?.total ?: 0L
                        
                        if (pullRefresh || currentPage == 1) {
                            rooms = roomList.map { it.toRoomtEntity() }
                        } else {
                            rooms = rooms + roomList.map { it.toRoomtEntity() }
                        }
                        
                        roomsHasMore = rooms.size < total
                        if (roomsHasMore && !pullRefresh) {
                            roomsCurrentPage++
                        }
                    } else {
                        Log.e("MyProfileViewModel", "loadRooms failed: ${response.code()}")
                    }
                }
            } catch (e: Exception) {
                Log.e("MyProfileViewModel", "loadRooms error: ", e)
            } finally {
                roomsLoading = false
                roomsRefreshing = false
            }
        }
    }

    /**
     * 加载更多房间
     * @param filterType 筛选类型：0=全部，1=公开，2=私有
     * @param ownerSessionId 创建者用户ID（ChatAIID），用于过滤特定创建者的房间
     */
    fun loadMoreRooms(filterType: Int = 0, ownerSessionId: String? = null) {
        if (roomsLoading || !roomsHasMore) return
        loadRooms(filterType = filterType, pullRefresh = false, ownerSessionId = ownerSessionId)
    }

    /**
     * 刷新房间列表
     * @param filterType 筛选类型：0=全部，1=公开，2=私有
     * @param ownerSessionId 创建者用户ID（ChatAIID），用于过滤特定创建者的房间
     */
    fun refreshRooms(filterType: Int = 0, ownerSessionId: String? = null) {
        rooms = emptyList()
        roomsCurrentPage = 1
        roomsHasMore = true
        loadRooms(filterType = filterType, pullRefresh = true, ownerSessionId = ownerSessionId)
    }
}