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

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.explorer.profile.GetCheersResponse
import kr.co.vividnext.sodalive.explorer.profile.cheers.PutModifyCheersRequest
import kr.co.vividnext.sodalive.report.ReportRepository
import kr.co.vividnext.sodalive.report.ReportRequest
import kr.co.vividnext.sodalive.report.ReportType

class UserProfileFantalkAllViewModel(
    private val repository: ExplorerRepository,
    private val reportRepository: ReportRepository
) : BaseViewModel() {

    var cheersPage = 1
    val pageSize = 10
    private var isCheersLast = false

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

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

    private var _cheersLiveData = MutableLiveData<GetCheersResponse>()
    val cheersLiveData: LiveData<GetCheersResponse>
        get() = _cheersLiveData

    fun getCheersList(creatorId: Long) {
        if (!isCheersLast && !_isLoading.value!!) {
            _isLoading.value = true

            compositeDisposable.add(
                repository.getCreatorProfileCheers(
                    creatorId = creatorId,
                    page = cheersPage,
                    size = pageSize,
                    token = "Bearer ${SharedPreferenceManager.token}"
                ).subscribe(
                    {
                        if (it.success && it.data != null) {
                            _cheersLiveData.postValue(it.data!!)
                            if (it.data.cheers.isNotEmpty()) {
                                cheersPage += 1
                            } else {
                                isCheersLast = true
                            }
                        } else {
                            if (it.message != null) {
                                _toastLiveData.postValue(it.message)
                            } else {
                                _toastLiveData.postValue(
                                    "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                )
                            }
                        }

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

    fun cheersReport(cheersId: Long, reason: String) {
        _isLoading.value = true

        val request = ReportRequest(ReportType.CHEERS, reason, cheersId = cheersId)
        compositeDisposable.add(
            reportRepository.report(
                request = request,
                token = "Bearer ${SharedPreferenceManager.token}"
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        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 writeCheers(parentCheersId: Long? = null, creatorId: Long, cheersContent: String) {
        if (cheersContent.isBlank()) {
            _toastLiveData.postValue("내용을 입력하세요")
            return
        }

        _isLoading.value = true

        compositeDisposable.add(
            repository.writeCheers(
                parentCheersId = parentCheersId,
                creatorId = creatorId,
                content = cheersContent,
                token = "Bearer ${SharedPreferenceManager.token}"
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        _isLoading.value = false

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

    fun modifyCheers(
        cheersId: Long,
        creatorId: Long,
        cheersContent: String? = null,
        isActive: Boolean? = null
    ) {
        if (cheersContent == null && isActive == null) {
            _toastLiveData.postValue("변경사항이 없습니다.")
            return
        }

        if (cheersContent != null && cheersContent.isBlank()) {
            _toastLiveData.postValue("내용을 입력하세요")
            return
        }

        _isLoading.value = true

        val request = PutModifyCheersRequest(cheersId = cheersId)

        if (cheersContent != null) {
            request.content = cheersContent
        }

        if (isActive != null) {
            request.isActive = isActive
        }

        compositeDisposable.add(
            repository.modifyCheers(
                request = request,
                token = "Bearer ${SharedPreferenceManager.token}"
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        _isLoading.value = false

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