package com.aiosman.riderpro.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.riderpro.data.UserServiceImpl
import com.aiosman.riderpro.entity.AccountPagingSource
import com.aiosman.riderpro.entity.AccountProfileEntity
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

object FollowingListViewModel : ViewModel() {
    private val userService = UserServiceImpl()
    private val _usersFlow = MutableStateFlow<PagingData<AccountProfileEntity>>(PagingData.empty())
    var isLoading by mutableStateOf(false)
    val usersFlow = _usersFlow.asStateFlow()
    private var userId by mutableStateOf<Int?>(null)
    fun loadData(id: Int, force: Boolean = false) {
        if (userId == id && !force) {
            return
        }
        isLoading = true
        userId = id
        viewModelScope.launch {
            Pager(
                config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                pagingSourceFactory = {
                    AccountPagingSource(
                        userService,
                        followingId = id
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _usersFlow.value = it
            }
        }
        isLoading = false
    }

    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())
        updateIsFollow(userId)
    }

    suspend fun unfollowUser(userId: Int) {
        userService.unFollowUser(userId.toString())
        updateIsFollow(userId, false)
    }

    fun ResetModel() {
        userId = null
    }

}