package uz.ssd.mobiuz.ui.forget


import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import uz.ssd.mobiuz.R
import uz.ssd.mobiuz.databinding.FragmentVerificationBinding
import uz.ssd.mobiuz.model.UserAuth
import uz.ssd.mobiuz.network.model.UiStateObject
import uz.ssd.mobiuz.ui.auth.AuthViewModel
import uz.ssd.mobiuz.ui.base.BaseFragment
import uz.ssd.mobiuz.ui.global.TextWatcherWrapper
import uz.ssd.mobiuz.utils.ButtonClick
import uz.ssd.mobiuz.utils.Utils
import uz.ssd.mobiuz.utils.extensions.hideKeyboard
import uz.ssd.mobiuz.utils.extensions.showKeyboard
import uz.ssd.mobiuz.utils.extensions.showMessage

@AndroidEntryPoint
class ForgetVerificationFragment : BaseFragment(R.layout.fragment_verification) {

    private var _bn: FragmentVerificationBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private val viewModel: AuthViewModel by viewModels()
    private val navController: NavController by lazy(LazyThreadSafetyMode.NONE) { NavHostFragment.findNavController(this) }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentVerificationBinding.bind(view)
        setUpUI()
        count(true)
        collects()
    }

    override fun setUpUI() {
        bn.apply {

            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }


            loadEdited()




            btnLogin.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    viewModel.login(UserAuth("phone", "password"))
                }
            })

            countWaitText.setTextColor(Color.parseColor("#97ADB6"))

            sentCodeAgain.setTextColor(Color.parseColor("#FF9500"))

            sentCodeAgain.setOnClickListener {
//                viewModel.login(UserAuth("",""))
                count(true)
            }
            coutdownView.setOnCountdownEndListener {
                count(false)
            }
        }
    }

    private fun loadEdited() {
        bn.apply {


            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }

            viewGroup.setOnClickListener {
                it.hideKeyboard()
            }

            frame.setOnClickListener {
                pin1.text?.clear()
                pin2.text?.clear()
                pin3.text?.clear()
                pin4.text?.clear()
                pin5.text?.clear()
                pin6.text?.clear()
                pin1.showKeyboard()
            }

            pin1.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    if (s.toString().isNotEmpty()) {
                        pin2.requestFocus()
                        pin1.setBackgroundResource(R.drawable.bgn_ver_checked)
                    } else {
                        pin1.setBackgroundResource(R.drawable.bgn_ver_unchecked)
                    }
                }

            })
            pin2.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    if (s.toString().isNotEmpty()) {
                        pin3.requestFocus()
                        pin2.setBackgroundResource(R.drawable.bgn_ver_checked)
                    } else {
                        pin1.requestFocus()
                        pin2.setBackgroundResource(R.drawable.bgn_ver_unchecked)
                    }
                }

            })
            pin3.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    if (s.toString().isNotEmpty()) {
                        pin4.requestFocus()
                        pin3.setBackgroundResource(R.drawable.bgn_ver_checked)
                    } else {
                        pin2.requestFocus()
                        pin3.setBackgroundResource(R.drawable.bgn_ver_unchecked)
                    }
                }

            })
            pin4.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    if (s.toString().isNotEmpty()) {
                        pin5.requestFocus()
                        pin4.setBackgroundResource(R.drawable.bgn_ver_checked)
                    } else {
                        pin3.requestFocus()
                        pin4.setBackgroundResource(R.drawable.bgn_ver_unchecked)
                    }
                }

            })
            pin5.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    if (s.toString().isNotEmpty()) {
                        pin6.requestFocus()
                        pin5.setBackgroundResource(R.drawable.bgn_ver_checked)
                    } else {
                        pin4.requestFocus()
                        pin5.setBackgroundResource(R.drawable.bgn_ver_unchecked)
                    }
                }

            })
            pin6.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    if (s.toString().isNotEmpty()) {
                        pin6.setBackgroundResource(R.drawable.bgn_ver_checked)
                        pin6.hideKeyboard()
                        btnLogin.isEnabled = true
                    } else {
                        pin5.requestFocus()
                        btnLogin.isEnabled = false
                        pin6.setBackgroundResource(R.drawable.bgn_ver_unchecked)
                    }
                }

            })

            pin1.setOnKeyListener { _, keyCode, _ ->
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    checkFocus().requestFocus()
                }
                false
            }
            pin2.setOnKeyListener { _, keyCode, _ ->
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    checkFocus().requestFocus()
                }
                false
            }
            pin3.setOnKeyListener { _, keyCode, _ ->
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    checkFocus().requestFocus()
                }
                false
            }
            pin4.setOnKeyListener { _, keyCode, _ ->
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    checkFocus().requestFocus()
                }
                false
            }
            pin5.setOnKeyListener { _, keyCode, _ ->
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    checkFocus().requestFocus()
                }
                false
            }
            pin6.setOnKeyListener { _, keyCode, _ ->
                if (keyCode == KeyEvent.KEYCODE_DEL) {
                    checkFocus().requestFocus()
                }
                false
            }
        }
    }

    private fun checkFocus(): View {
        bn.apply {
            return when {
                pin6.text.toString().trim().isNotEmpty() -> {
                    pin6.text?.clear()
                    return pin6
                }
                pin5.text.toString().trim().isNotEmpty() -> {
                    pin5.text?.clear()
                    return pin5
                }
                pin4.text.toString().trim().isNotEmpty() -> {
                    pin4.text?.clear()
                    return pin4
                }
                pin3.text.toString().trim().isNotEmpty() -> {
                    pin3.text?.clear()
                    return pin3
                }
                pin2.text.toString().trim().isNotEmpty() -> {
                    pin2.text?.clear()
                    return pin2
                }
                else -> {
                    pin1.text?.clear()
                    pin1
                }
            }
        }
    }

    override fun collects() {
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.loginUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        navController.navigate(R.id.forgetPasswordFragment, null, Utils.navOptions())
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        showMessage(it.message)
                    }
                    is UiStateObject.LOADING -> {
                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }
    }

    private fun count(status: Boolean) {
        bn.apply {
            sentCodeAgain.isVisible = !status
            countWaitText.isVisible = status
            coutdownView.isVisible = status
            if (status) coutdownView.start(120000)
        }
    }

    override fun onDestroy() {
        _bn = null
        super.onDestroy()
    }

}

