package com.aiosman.riderpro.ui.comment.notice

import android.content.Context
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.AccountService
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.CommentRemoteDataSource
import com.aiosman.riderpro.data.CommentService
import com.aiosman.riderpro.data.CommentServiceImpl
import com.aiosman.riderpro.data.UserService
import com.aiosman.riderpro.data.UserServiceImpl
import com.aiosman.riderpro.entity.CommentEntity
import com.aiosman.riderpro.entity.CommentPagingSource

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class CommentNoticeListViewModel : ViewModel() {
    val accountService: AccountService = AccountServiceImpl()
    val userService: UserService = UserServiceImpl()
    private val commentService: CommentService = CommentServiceImpl()
    private val _commentItemsFlow = MutableStateFlow<PagingData<CommentEntity>>(PagingData.empty())
    val commentItemsFlow = _commentItemsFlow.asStateFlow()
    var isLoading by mutableStateOf(false)
    var isFirstLoad = true
    fun initData(context: Context, force: Boolean = false) {
        if (!isFirstLoad && !force) {
            return
        }
        if (force) {
            isLoading = true
        }
        isFirstLoad = false
        viewModelScope.launch {
            Pager(
                config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                pagingSourceFactory = {
                    CommentPagingSource(
                        CommentRemoteDataSource(commentService),
                        selfNotice = true,
                        order = "latest"
                    )
                }
            ).flow.cachedIn(viewModelScope).collectLatest {
                _commentItemsFlow.value = it
            }
        }

        isLoading = false

    }

    private fun updateIsRead(id: Int) {
        val currentPagingData = _commentItemsFlow.value
        val updatedPagingData = currentPagingData.map { commentEntity ->
            if (commentEntity.id == id) {
                commentEntity.copy(unread = false)
            } else {
                commentEntity
            }
        }
        _commentItemsFlow.value = updatedPagingData
    }

    fun updateReadStatus(id: Int) {
        viewModelScope.launch {
            commentService.updateReadStatus(id)
            updateIsRead(id)
        }
    }
}