package kr.co.vividnext.sodalive.message.text

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.IntentCompat
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.Constants
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.databinding.ActivityTextMessageWriteBinding
import kr.co.vividnext.sodalive.live.room.detail.GetRoomDetailUser
import kr.co.vividnext.sodalive.message.SelectMessageRecipientActivity
import org.koin.android.ext.android.inject
import java.util.concurrent.TimeUnit

class TextMessageWriteActivity : BaseActivity<ActivityTextMessageWriteBinding>(
    ActivityTextMessageWriteBinding::inflate
) {
    private val viewModel: TextMessageWriteViewModel by inject()

    private lateinit var loadingDialog: LoadingDialog
    private lateinit var activityResultLauncher: ActivityResultLauncher<Intent>

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        activityResultLauncher = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) {
            if (it.resultCode == Activity.RESULT_OK) {
                if (it.data != null) {
                    val recipient = IntentCompat.getParcelableExtra(
                        it.data!!,
                        Constants.EXTRA_SELECT_RECIPIENT,
                        GetRoomDetailUser::class.java
                    )

                    if (recipient != null) {
                        binding.tvRecipientNickname.text = recipient.nickname
                        viewModel.recipientId = recipient.id
                    }
                }
            }
        }

        bindData()
    }

    @SuppressLint("SetTextI18n")
    override fun setupView() {
        loadingDialog = LoadingDialog(this, layoutInflater)

        val replySenderNickname = intent.getStringExtra(Constants.EXTRA_NICKNAME)
        val replySenderId = intent.getLongExtra(Constants.EXTRA_USER_ID, 0)

        if (replySenderId > 0 && replySenderNickname != null) {
            binding.ivSelectRecipient.visibility = View.GONE
            binding.tvRecipientNickname.text = replySenderNickname
            viewModel.recipientId = replySenderId

            binding.tvTitle.text = "메시지 보내기"
        }

        binding.tvCancel.setOnClickListener { finish() }

        binding.tvSend.setOnClickListener {
            viewModel.write {
                Toast.makeText(
                    applicationContext,
                    "메시지 전송이 완료되었습니다.",
                    Toast.LENGTH_LONG
                ).show()

                setResult(RESULT_OK)
                finish()
            }
        }

        binding.ivSelectRecipient.setOnClickListener {
            val intent = Intent(applicationContext, SelectMessageRecipientActivity::class.java)
            activityResultLauncher.launch(intent)
        }
    }

    private fun bindData() {
        compositeDisposable.add(
            binding.etMessage.textChanges().skip(1)
                .debounce(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe {
                    viewModel.textMessage = 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()
            }
        }
    }
}
