package kr.co.vividnext.sodalive.live.room.menu

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.live.room.create.LiveRoomCreateViewModel

class MenuConfigViewModel(private val repository: MenuConfigRepository) : BaseViewModel() {

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

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

    private val _selectedMenuLiveData = MutableLiveData<LiveRoomCreateViewModel.SelectedMenu>()
    val selectedMenuLiveData: LiveData<LiveRoomCreateViewModel.SelectedMenu>
        get() = _selectedMenuLiveData

    private val _selectedMenuTextLiveData = MutableLiveData("")
    val selectedMenuTextLiveData: LiveData<String>
        get() = _selectedMenuTextLiveData

    private var menuId = 0L
    private val menuList = mutableListOf<GetMenuPresetResponse>()

    var menuText: String = ""

    fun getAllMenuPreset(selectedMenu: LiveRoomCreateViewModel.SelectedMenu = LiveRoomCreateViewModel.SelectedMenu.MENU_1) {
        _isLoading.value = true

        compositeDisposable.add(
            repository.getAllMenu(
                creatorId = SharedPreferenceManager.userId,
                token = "Bearer ${SharedPreferenceManager.token}"
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        if (it.success) {
                            val data = it.data ?: listOf()
                            menuList.clear()
                            menuList.addAll(data)
                            selectMenuPreset(selectedMenu)
                        } 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 selectMenuPreset(selectedMenuPreset: LiveRoomCreateViewModel.SelectedMenu) {
        if (
            menuList.isEmpty() &&
            (
                selectedMenuPreset == LiveRoomCreateViewModel.SelectedMenu.MENU_2 ||
                    selectedMenuPreset == LiveRoomCreateViewModel.SelectedMenu.MENU_3
                )
        ) {
            _toastLiveData.value = "메뉴 1을 먼저 설정하세요"
            return
        }

        if (menuList.size == 1 && selectedMenuPreset == LiveRoomCreateViewModel.SelectedMenu.MENU_3) {
            _toastLiveData.value = "메뉴 1과 메뉴 2를 먼저 설정하세요"
            return
        }

        if (_selectedMenuLiveData.value != selectedMenuPreset) {
            _selectedMenuLiveData.value = selectedMenuPreset

            if (menuList.size > selectedMenuPreset.ordinal) {
                val menuPreset = menuList[selectedMenuPreset.ordinal]

                menuText = menuPreset.menu
                menuId = menuPreset.id
                _selectedMenuTextLiveData.value = menuPreset.menu
            } else {
                menuText = ""
                menuId = 0
                _selectedMenuTextLiveData.value = ""
            }
        }
    }

    fun saveMenu() {
        if (menuText == _selectedMenuTextLiveData.value) {
            _toastLiveData.postValue("저장되었습니다.")
            return
        }

        _isLoading.value = true
        compositeDisposable.add(
            repository.saveMenu(
                menuId = menuId,
                menu = menuText,
                token = "Bearer ${SharedPreferenceManager.token}"
            )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    {
                        if (it.success) {
                            _toastLiveData.postValue("저장되었습니다.")
                            getAllMenuPreset(selectedMenu = _selectedMenuLiveData.value!!)
                        } 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 countMenu() = menuList.size
}
