package kr.co.vividnext.sodalive.explorer.profile.donation

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.orhanobut.logger.Logger
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kr.co.vividnext.sodalive.base.BaseViewModel
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.explorer.ExplorerRepository
import kr.co.vividnext.sodalive.mypage.profile.ProfileUpdateRequest
import kr.co.vividnext.sodalive.user.UserRepository

class UserProfileDonationAllViewModel(
    private val repository: ExplorerRepository,
    private val memberRepository: UserRepository
) : BaseViewModel() {

    private val _toastLiveData = MutableLiveData<String?>()
    val toastLiveData: LiveData<String?>
        get() = _toastLiveData

    private var _isLoading = MutableLiveData(false)
    val isLoading: LiveData<Boolean>
        get() = _isLoading

    private var _donationLiveData = MutableLiveData<GetDonationAllResponse>()
    val donationLiveData: LiveData<GetDonationAllResponse>
        get() = _donationLiveData

    private var _isVisibleDonationRank = MutableLiveData<Boolean>()
    val isVisibleDonationRank: LiveData<Boolean>
        get() = _isVisibleDonationRank

    private var isLast = false
    private var page = 1
    private val size = 10

    fun getCreatorProfileDonationRanking(userId: Long) {
        if (!_isLoading.value!! && !isLast) {
            _isLoading.value = true

            compositeDisposable.add(
                repository.getCreatorProfileDonationRanking(
                    id = userId,
                    page = page,
                    size = size,
                    token = "Bearer ${SharedPreferenceManager.token}"
                )
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                        {
                            if (it.success && it.data != null) {
                                if (it.data.userDonationRanking.isNotEmpty()) {
                                    page += 1
                                    _donationLiveData.postValue(it.data!!)
                                } else {
                                    isLast = true
                                }
                                _isVisibleDonationRank.postValue(it.data.isVisibleDonationRank)
                            } else {
                                if (it.message != null) {
                                    _toastLiveData.postValue(it.message)
                                } else {
                                    _toastLiveData.postValue(
                                        "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                    )
                                }
                            }

                            _isLoading.value = false
                        },
                        {
                            _isLoading.value = false
                            it.message?.let { message -> Logger.e(message) }
                            _toastLiveData.postValue("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                        }
                    )
            )
        }
    }

    fun refresh(userId: Long) {
        page = 1
        isLast = false
        getCreatorProfileDonationRanking(userId)
    }

    fun onClickToggleVisibleDonationRank() {
        val nowStateVisibleDonationRank = _isVisibleDonationRank.value!!

        _isLoading.value = true
        compositeDisposable.add(
            memberRepository.updateProfile(
                request = ProfileUpdateRequest(
                    email = SharedPreferenceManager.email,
                    isVisibleDonationRank = !nowStateVisibleDonationRank
                ),
                token = "Bearer ${SharedPreferenceManager.token}"
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        if (it.success) {
                            _isVisibleDonationRank.postValue(!nowStateVisibleDonationRank)
                        } else {
                            if (it.message != null) {
                                _toastLiveData.postValue(it.message)
                            } else {
                                _toastLiveData.postValue(
                                    "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                )
                            }
                        }

                        _isLoading.value = false
                    },
                    {
                        _isLoading.value = false
                        it.message?.let { message -> Logger.e(message) }
                        _toastLiveData.postValue("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                    }
                )
        )
    }
}
