package kr.co.vividnext.sodalive.live.reservation_status

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import coil.load
import coil.transform.RoundedCornersTransformation
import com.jakewharton.rxbinding4.widget.textChanges
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.base.BaseActivity
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.databinding.ActivityLiveReservationCancelBinding
import kr.co.vividnext.sodalive.extensions.dpToPx
import kr.co.vividnext.sodalive.main.MainActivity
import kr.co.vividnext.sodalive.mypage.can.status.CanStatusActivity
import org.koin.android.ext.android.inject

class LiveReservationCancelActivity : BaseActivity<ActivityLiveReservationCancelBinding>(
    ActivityLiveReservationCancelBinding::inflate
) {

    private val viewModel: LiveReservationStatusViewModel by inject()
    private lateinit var loadingDialog: LoadingDialog
    private var reservationId: Long = 0

    private val onBackPressedCallback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            setResult(RESULT_OK)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        onBackPressedDispatcher.addCallback(this, onBackPressedCallback)

        reservationId = intent.getLongExtra("reservation_id", 0)
        if (reservationId <= 0) {
            Toast.makeText(applicationContext, "잘못된 예약정보 입니다.", Toast.LENGTH_LONG).show()
            finish()
            return
        }

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

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

        compositeDisposable.add(
            binding.etReasonEtc.textChanges().skip(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    if (binding.tvReason5.isSelected) {
                        viewModel.reason = it.toString()
                    }
                }
        )

        viewModel.reservationId = reservationId
        viewModel.getReservation { setReservation(it) }
    }

    @SuppressLint("SetTextI18n")
    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)
        binding.toolbar.tvBack.text = "예약취소"
        binding.toolbar.tvBack.setOnClickListener { finish() }

        binding.tvReason1.setOnClickListener {
            checkboxSelectedFalse()
            binding.tvReason1.isSelected = true
            viewModel.reason = binding.tvReason1.text.toString()
        }

        binding.tvReason2.setOnClickListener {
            checkboxSelectedFalse()
            binding.tvReason2.isSelected = true
            viewModel.reason = binding.tvReason2.text.toString()
        }

        binding.tvReason3.setOnClickListener {
            checkboxSelectedFalse()
            binding.tvReason3.isSelected = true
            viewModel.reason = binding.tvReason3.text.toString()
        }

        binding.tvReason4.setOnClickListener {
            checkboxSelectedFalse()
            binding.tvReason4.isSelected = true
            viewModel.reason = binding.tvReason4.text.toString()
        }

        binding.tvReason5.setOnClickListener {
            checkboxSelectedFalse()
            binding.tvReason5.isSelected = true
            viewModel.reason = binding.etReasonEtc.text.toString()
        }

        binding.tvOtherSudaReservation.setOnClickListener {
            finishAffinity()
            startActivity(Intent(applicationContext, MainActivity::class.java))
        }

        binding.tvCheckCanStatus.setOnClickListener {
            startActivity(Intent(applicationContext, CanStatusActivity::class.java))
        }

        binding.tvCancel.setOnClickListener {
            viewModel.cancelReservation {
                if (binding.tvPrice.text == "무료") {
                    binding.tvCancelComplete.visibility = View.GONE
                } else {
                    binding.tvCancelComplete.visibility = View.VISIBLE
                    binding.tvCancelComplete.text = "결제한 ${binding.tvPrice.text}이 \n환불처리 되었습니다."
                }
                binding.llCancelComplete.visibility = View.VISIBLE
                binding.llCancelConfirm.visibility = View.GONE
                binding.toolbar.tvBack.text = "예약취소 확인"
            }
        }
    }

    private fun checkboxSelectedFalse() {
        binding.tvReason1.isSelected = false
        binding.tvReason2.isSelected = false
        binding.tvReason3.isSelected = false
        binding.tvReason4.isSelected = false
        binding.tvReason5.isSelected = false
    }

    @SuppressLint("SetTextI18n")
    private fun setReservation(response: GetLiveReservationResponse) {
        binding.tvDate.text = response.beginDateTime
        binding.tvNickname.text = response.masterNickname
        binding.tvTitle.text = response.title
        binding.ivProfile.load(response.coverImageUrl) {
            crossfade(true)
            placeholder(R.drawable.ic_place_holder)
            transformations(RoundedCornersTransformation(4.7f.dpToPx()))
        }

        if (response.price > 0) {
            binding.tvCheckCanStatus.visibility = View.VISIBLE
            binding.tvPrice.text = "${response.price}캔"
        } else {
            binding.tvCheckCanStatus.visibility = View.GONE
            binding.tvPrice.text = "무료"
        }
    }
}
