package uz.ssd.mobiuz.ui.auth

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.base.BaseFragment
import uz.ssd.mobiuz.ui.global.TextWatcherWrapper
import uz.ssd.mobiuz.utils.ButtonClick
import uz.ssd.mobiuz.utils.CONSTANTS
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 VerificationFragment : 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) }
    private var code = ""


    private var phone = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            phone = it.getString(CONSTANTS.PHONE) ?: ""
        }
    }
    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()

            viewGroup.setOnClickListener(object : ButtonClick(){
                override fun onSingleClick(v: View?) {
                    v?.hideKeyboard()
                }
            })

            frame.setOnClickListener(object : ButtonClick(){
                override fun onSingleClick(v: View?) {
                    clearPins()
                }
            })

            btnLogin.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    getLinePinCodes()
                    if(code.length == 6){
                        viewModel.verification(UserAuth(phone, null,code))
                    }else{
                        clearPins()
                    }
                }
            })

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

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

            sentCodeAgain.setOnClickListener {
                count(true)
            }
            coutdownView.setOnCountdownEndListener {
                count(false)
            }
        }
    }

    private fun getLinePinCodes() {
        bn.apply {
            code = ""
            code += pin1.text.toString()
            code += pin2.text.toString()
            code += pin3.text.toString()
            code += pin4.text.toString()
            code += pin5.text.toString()
            code += pin6.text.toString()
        }
    }


    private fun clearPins() {
        bn.apply {
            pin1.text?.clear()
            pin2.text?.clear()
            pin3.text?.clear()
            pin4.text?.clear()
            pin5.text?.clear()
            pin6.text?.clear()
            pin1.showKeyboard()
        }
    }
    private fun loadEdited() {
        bn.apply {


            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)
                    }
                }
            })

            for (i in 0 until pinView.childCount){
                pinView.getChildAt(i).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.verificationUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        navController.navigate(R.id.pinFragment, 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(60000)
        }
    }

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

}
