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.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 cn.jpush.android.api.JPushInterface
import com.aiosman.riderpro.AppState
import com.aiosman.riderpro.AppStore
import com.aiosman.riderpro.JpushService
import com.aiosman.riderpro.Messaging
import com.aiosman.riderpro.data.AccountProfile
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.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 kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.io.File

object MyProfileViewModel : ViewModel() {
    val accountService: AccountService = AccountServiceImpl()
    val momentService: MomentService = MomentServiceImpl()
    var profile by mutableStateOf<AccountProfileEntity?>(null)
    private var _sharedFlow = MutableStateFlow<PagingData<MomentEntity>>(PagingData.empty())
    var sharedFlow = _sharedFlow.asStateFlow()

    var refreshing by mutableStateOf(false)
    var firstLoad = true
    suspend fun loadUserProfile() {
        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()
            refreshing = false
            profile?.let {
                try {
                    // Collect shared flow
                    Pager(
                        config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                        pagingSourceFactory = {
                            MomentPagingSource(
                                MomentRemoteDataSource(momentService),
                                author = AppState.UserId
                            )
                        }
                    ).flow.cachedIn(viewModelScope).collectLatest {
                        _sharedFlow.value = it
                    }
                } catch (e: Exception) {
                    Log.e("MyProfileViewModel", "loadProfile: ", e)
                }
            }

        }
    }

    fun logout(context: Context) {
        viewModelScope.launch {
            Messaging.unregisterDevice(context)
            AppStore.apply {
                token = null
                rememberMe = false
                saveData()
            }
            // 删除推送渠道
            AppState.ReloadAppState(context)
        }

    }

    fun updateUserProfileBanner(bannerImageUrl: Uri?,file:File, context: Context) {
        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()
        }
    }

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

    fun ResetModel() {
        profile = null
        _sharedFlow.value = PagingData.empty()
        firstLoad = true
    }
}