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

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kr.co.vividnext.sodalive.audio_content.order.GetAudioContentOrderListItem
import kr.co.vividnext.sodalive.audio_content.playlist.AudioContentPlaylistRepository
import kr.co.vividnext.sodalive.audio_content.playlist.detail.AudioContentPlaylistContent
import kr.co.vividnext.sodalive.base.BaseViewModel
import kr.co.vividnext.sodalive.common.SharedPreferenceManager

class AudioContentPlaylistCreateViewModel(
    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

    val contentList = mutableListOf<AudioContentPlaylistContent>()

    var title: String = ""
    var desc: String = ""

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

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

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

            compositeDisposable.add(
                repository.createPlaylist(
                    request = CreatePlaylistRequest(
                        title = title,
                        desc = desc,
                        contentIdAndOrderList = contentIdAndOrderList
                    ),
                    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
    }
}
