package com.aiosman.ravenow.ui.follower

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.map
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.entity.AccountPagingSource
import com.aiosman.ravenow.entity.AccountProfileEntity
import com.aiosman.ravenow.event.FollowChangeEvent
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

open class BaseFollowModel:ViewModel() {
    private val userService = UserServiceImpl()
    private val _usersFlow = MutableStateFlow<PagingData<AccountProfileEntity>>(PagingData.empty())
    val usersFlow = _usersFlow.asStateFlow()
    var isLoading by mutableStateOf(false)
    open var followerId: Int? = null
    open var followingId: Int? = null
    init {
        EventBus.getDefault().register(this)
    }
    fun loadData(id: Int,force : Boolean = false) {
        if (isLoading) return
        isLoading = true
        viewModelScope.launch {
            Pager(
                config = PagingConfig(pageSize = 20, enablePlaceholders = false),
                pagingSourceFactory = {
                    AccountPagingSource(
                        userService,
                        followerId = followerId,
                        followingId = followingId
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _usersFlow.value = it
            }
        }
        isLoading = false
    }

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

    private fun updateIsFollow(id: Int, isFollow: Boolean = true) {
        val currentPagingData = usersFlow.value
        val updatedPagingData = currentPagingData.map { user ->
            if (user.id == id) {
                user.copy(isFollowing = isFollow)
            } else {
                user
            }
        }
        _usersFlow.value = updatedPagingData
    }

    suspend fun followUser(userId: Int) {
        userService.followUser(userId.toString())
        EventBus.getDefault().post(FollowChangeEvent(userId, true))
    }

    suspend fun unFollowUser(userId: Int) {
        userService.unFollowUser(userId.toString())
        EventBus.getDefault().post(FollowChangeEvent(userId, false))
    }

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