package kr.co.vividnext.sodalive.live.roulette.config

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Service
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.InputFilter
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
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.BaseFragment
import kr.co.vividnext.sodalive.common.Constants
import kr.co.vividnext.sodalive.common.LoadingDialog
import kr.co.vividnext.sodalive.databinding.FragmentRouletteSettingsBinding
import kr.co.vividnext.sodalive.live.roulette.RoulettePreviewDialog
import org.koin.android.ext.android.inject
import java.util.concurrent.TimeUnit

class RouletteSettingsFragment : BaseFragment<FragmentRouletteSettingsBinding>(
    FragmentRouletteSettingsBinding::inflate
) {
    private val viewModel: RouletteSettingsViewModel by inject()

    private lateinit var imm: InputMethodManager
    private lateinit var loadingDialog: LoadingDialog

    private val handler = Handler(Looper.getMainLooper())

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupView()
        bindData()
        viewModel.getRoulette()
    }

    private fun setupView() {
        loadingDialog = LoadingDialog(requireActivity(), layoutInflater)
        imm = requireActivity().getSystemService(
            Service.INPUT_METHOD_SERVICE
        ) as InputMethodManager

        binding.etSetPrice.filters = arrayOf(InputFilter { source, start, end, _, _, _ ->
            // Only allow numeric input
            for (i in start until end) {
                if (!Character.isDigit(source[i])) {
                    return@InputFilter ""
                }
            }
            null
        })

        binding.ivRouletteIsActive.setOnClickListener { viewModel.toggleIsActive() }
        binding.ivAddOption.setOnClickListener { addOption() }

        binding.tvPreview.setOnClickListener {
            handler.postDelayed({
                imm.hideSoftInputFromWindow(view?.windowToken, 0)
            }, 100)
            viewModel.onClickPreview()
        }

        binding.tvSave.setOnClickListener { _ ->
            handler.postDelayed({
                imm.hideSoftInputFromWindow(view?.windowToken, 0)
            }, 100)
            viewModel.createOrUpdateRoulette {
                val resultIntent = Intent().apply { putExtra(Constants.EXTRA_RESULT_ROULETTE, it) }
                requireActivity().setResult(Activity.RESULT_OK, resultIntent)
                requireActivity().finish()
            }
        }
    }

    private fun bindData() {
        viewModel.isActiveLiveData.observe(viewLifecycleOwner) {
            binding.ivRouletteIsActive.setImageResource(
                if (it) R.drawable.btn_toggle_on_big else R.drawable.btn_toggle_off_big
            )
        }

        viewModel.optionsLiveData.observe(viewLifecycleOwner) { updateOptionUi(it) }

        viewModel.toastLiveData.observe(viewLifecycleOwner) { it?.let { showToast(it) } }

        viewModel.canLiveData.observe(viewLifecycleOwner) {
            if (it > 0) {
                binding.etSetPrice.setText("$it")
            } else {
                binding.etSetPrice.setText("")
            }
        }

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

        viewModel.roulettePreviewLiveData.observe(viewLifecycleOwner) {
            RoulettePreviewDialog(
                activity = requireActivity(),
                preview = it,
                title = "룰렛 미리보기",
                layoutInflater = layoutInflater
            ).show()
        }

        compositeDisposable.add(
            binding.etSetPrice.textChanges().skip(1)
                .debounce(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe {
                    if (it.trim().isNotEmpty()) {
                        viewModel.can = it.toString().toInt()
                    }
                }
        )
    }

    private fun addOption() {
        val newOption = RouletteOption("", 1)
        viewModel.addOption(newOption)
    }

    private fun updateOptionUi(options: List<RouletteOption>) {
        binding.llRouletteOptionContainer.removeAllViews()
        options.forEachIndexed { index, option ->
            binding.llRouletteOptionContainer.addView(createOptionView(index, option))
        }
    }

    @SuppressLint("SetTextI18n")
    private fun createOptionView(index: Int, option: RouletteOption): View {
        val optionView = LayoutInflater
            .from(context)
            .inflate(
                R.layout.layout_roulette_option,
                binding.llRouletteOptionContainer,
                false
            )

        val etOption = optionView.findViewById<EditText>(R.id.et_option)
        val tvOptionTitle = optionView.findViewById<TextView>(R.id.tv_option_title)
        val tvPercentage = optionView.findViewById<TextView>(R.id.tv_option_percentage)
        val ivMinus = optionView.findViewById<ImageView>(R.id.iv_minus)
        val ivPlus = optionView.findViewById<ImageView>(R.id.iv_plus)
        val tvDelete = optionView.findViewById<TextView>(R.id.tv_delete)

        etOption.setText(option.title)
        tvOptionTitle.text = "옵션 ${index + 1}"
        tvPercentage.text = "${option.percentage}%"
        ivMinus.setOnClickListener { viewModel.subtractWeight(index) }
        ivPlus.setOnClickListener { viewModel.plusWeight(index) }

        if (index == 0 || index == 1) {
            tvDelete.visibility = View.GONE
        } else {
            tvDelete.visibility = View.VISIBLE
            tvDelete.setOnClickListener { viewModel.deleteOption(index) }
        }

        compositeDisposable.add(
            etOption.textChanges().skip(1)
                .debounce(100, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe {
                    viewModel.inputOption(index, it.toString())
                }
        )

        return optionView
    }
}
