package kr.co.vividnext.sodalive.mypage.profile.nickname

import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.Toast
import com.jakewharton.rxbinding4.widget.textChanges
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kr.co.vividnext.sodalive.base.BaseActivity
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.common.SharedPreferenceManager
import kr.co.vividnext.sodalive.databinding.ActivityNicknameUpdateBinding
import org.koin.android.ext.android.inject
import java.util.concurrent.TimeUnit

class NicknameUpdateActivity : BaseActivity<ActivityNicknameUpdateBinding>(
    ActivityNicknameUpdateBinding::inflate
) {

    private val viewModel: NicknameUpdateViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        bindData()
        viewModel.getChangeNicknamePrice()

        binding.etNickname.setText(SharedPreferenceManager.nickname)
    }

    override fun setupView() {
        binding.toolbar.tvBack.text = "닉네임 변경"
        binding.toolbar.tvBack.setOnClickListener { finish() }

        loadingDialog = LoadingDialog(this, layoutInflater)

        binding.tvCheckNickname.setOnClickListener {
            viewModel.checkNickname()
        }

        binding.tvChangeNickname.setOnClickListener {
            viewModel.changeNickname { finish() }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun bindData() {
        compositeDisposable.add(
            binding.etNickname.textChanges().skip(1)
                .debounce(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe {
                    viewModel.isCheckedNickname = false
                    viewModel.nickname = it.toString()
                }
        )

        viewModel.toastLiveData.observe(this) {
            it?.let {
                Toast.makeText(applicationContext, it, Toast.LENGTH_LONG).show()
            }
        }

        viewModel.isLoading.observe(this) {
            if (it) {
                loadingDialog.show(screenWidth)
            } else {
                loadingDialog.dismiss()
            }
        }

        viewModel.priceLiveData.observe(this) {
            if (it > 0) {
                binding.tvChangeNickname.text = "${it}캔으로 닉네임 변경하기"
            } else {
                binding.tvChangeNickname.text = "닉네임 변경하기"
            }
        }
    }
}
