package com.aiosman.riderpro.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.remember
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 com.aiosman.riderpro.AppStore
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.MomentService
import com.aiosman.riderpro.data.UploadImage
import com.aiosman.riderpro.data.UserServiceImpl
import com.aiosman.riderpro.entity.AccountProfileEntity
import com.aiosman.riderpro.entity.MomentEntity
import com.aiosman.riderpro.entity.MomentPagingSource
import com.aiosman.riderpro.entity.MomentRemoteDataSource
import com.aiosman.riderpro.entity.MomentServiceImpl
import com.aiosman.riderpro.ui.post.NewPostViewModel.uriToFile
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

object MyProfileViewModel : ViewModel() {
    val accountService: AccountService = AccountServiceImpl()
    val momentService: MomentService = MomentServiceImpl()
    var profile by mutableStateOf<AccountProfileEntity?>(null)
    private var _momentsFlow = MutableStateFlow<PagingData<MomentEntity>>(PagingData.empty())
    var momentsFlow = _momentsFlow.asStateFlow()
    var refreshing by mutableStateOf(false)
    var firstLoad = true
    fun loadProfile(pullRefresh: Boolean = false) {
        if (!firstLoad && !pullRefresh) {
            return
        }
        viewModelScope.launch {
            if (pullRefresh){
                refreshing = true
            }
            firstLoad = false
            val profile = accountService.getMyAccountProfile()
            this@MyProfileViewModel.profile = profile
            refreshing = false
            try {
                Pager(
                    config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                    pagingSourceFactory = {
                        MomentPagingSource(
                            MomentRemoteDataSource(momentService),
                            author = profile.id
                        )
                    }
                ).flow.cachedIn(viewModelScope).collectLatest {
                    _momentsFlow.value = it
                }
            }catch (e: Exception){
                Log.e("MyProfileViewModel", "loadProfile: ", e)
            }


        }
    }

    suspend fun logout() {
        AppStore.apply {
            token = null
            rememberMe = false
            saveData()
        }
    }

    fun updateUserProfileBanner(bannerImageUrl: Uri?, context: Context) {
        viewModelScope.launch {
            var newBanner = bannerImageUrl?.let {
                val cursor = context.contentResolver.query(it, null, null, null, null)
                var newBanner: UploadImage? = null
                cursor?.use { cur ->
                    if (cur.moveToFirst()) {
                        val displayName = cur.getString(cur.getColumnIndex("_display_name"))
                        val extension = displayName.substringAfterLast(".")
                        Log.d("NewPost", "File name: $displayName, extension: $extension")
                        // read as file
                        val file = uriToFile(context, it)
                        Log.d("NewPost", "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()
        }
    }

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


}