package kr.co.vividnext.sodalive.audio_content.playlist.modify

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.audio_content.playlist.AudioContentPlaylistRepository
import kr.co.vividnext.sodalive.audio_content.playlist.create.PlaylistContentIdAndOrder
import kr.co.vividnext.sodalive.audio_content.playlist.detail.AudioContentPlaylistContent
import kr.co.vividnext.sodalive.audio_content.playlist.detail.GetPlaylistDetailResponse
import kr.co.vividnext.sodalive.base.BaseViewModel
import kr.co.vividnext.sodalive.common.SharedPreferenceManager

class AudioContentPlaylistModifyViewModel(
    private val repository: AudioContentPlaylistRepository
) : BaseViewModel() {
    private val _toastLiveData = MutableLiveData<String?>()
    val toastLiveData: LiveData<String?>
        get() = _toastLiveData

    private val _contentListLiveData = MutableLiveData<List<AudioContentPlaylistContent>>()
    val contentListLiveData: LiveData<List<AudioContentPlaylistContent>>
        get() = _contentListLiveData

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

    private val _detailResponseLiveData = MutableLiveData<GetPlaylistDetailResponse>()
    val detailResponseLiveData: LiveData<GetPlaylistDetailResponse>
        get() = _detailResponseLiveData

    val contentList = mutableListOf<AudioContentPlaylistContent>()

    var title: String = ""
    var desc: String = ""
    private var playlistId: Long = 0

    fun addContentId(item: AudioContentPlaylistContent) {
        contentList.add(item)
        _contentListLiveData.value = contentList
    }

    fun removeContentId(item: AudioContentPlaylistContent) {
        contentList.remove(item)
        _contentListLiveData.value = contentList
    }

    fun modifyPlaylist(onSuccess: () -> Unit) {
        if (validate()) {
            _isLoading.value = true
            val contentIdAndOrderList = contentList.mapIndexed { index, item ->
                PlaylistContentIdAndOrder(item.id, index + 1)
            }

            val request = UpdatePlaylistRequest(
                title = if (_detailResponseLiveData.value!!.title != title) {
                    title
                } else {
                    null
                },
                desc = if (_detailResponseLiveData.value!!.desc != desc) {
                    desc
                } else {
                    null
                },
                contentIdAndOrderList = contentIdAndOrderList
            )

            compositeDisposable.add(
                repository.updatePlaylist(
                    playlistId = playlistId,
                    request = request,
                    token = "Bearer ${SharedPreferenceManager.token}"
                )
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(
                        {
                            _isLoading.value = false
                            if (it.success) {
                                onSuccess()
                            } else {
                                if (it.message != null) {
                                    _toastLiveData.value = it.message
                                } else {
                                    _toastLiveData.value = "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                                }
                            }
                        },
                        {
                            _isLoading.value = false
                            if (it.message != null) {
                                _toastLiveData.value = it.message
                            } else {
                                _toastLiveData.value = "알 수 없는 오류가 발생했습니다. 다시 시도해 주세요."
                            }
                        }
                    )
            )
        }
    }

    private fun validate(): Boolean {
        if (title.isBlank() || title.length < 3) {
            _toastLiveData.value = "제목을 3자 이상 입력하세요"
            return false
        }

        if (contentList.isEmpty()) {
            _toastLiveData.value = "콘텐츠를 1개 이상 추가하세요"
            return false
        }

        return true
    }

    fun getPlaylistDetail(playlistId: Long) {
        this.playlistId = playlistId
        _isLoading.value = true
        compositeDisposable.add(
            repository.getPlaylistDetail(
                playlistId = playlistId,
                token = "Bearer ${SharedPreferenceManager.token}"
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        if (it.success && it.data != null) {
                            val data = it.data
                            _detailResponseLiveData.value = data!!
                            this.contentList.addAll(data.contentList)
                        } 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("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
                    }
                )
        )
    }
}
