package uz.mobiuz.mobiservice.dev.ui.auth.check

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.animation.AnimationUtils
import androidx.core.os.bundleOf
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.databinding.FragmentCheckPhoneBinding
import uz.mobiuz.mobiservice.dev.model.UserAuth
import uz.mobiuz.mobiservice.dev.network.model.UiStateObject
import uz.mobiuz.mobiservice.dev.ui.auth.AuthViewModel
import uz.mobiuz.mobiservice.dev.ui.base.BaseFragment
import uz.mobiuz.mobiservice.dev.ui.global.ButtonClick
import uz.mobiuz.mobiservice.dev.ui.global.CONSTANTS
import uz.mobiuz.mobiservice.dev.ui.global.TextWatcherWrapper
import uz.mobiuz.mobiservice.dev.utils.Utils
import uz.mobiuz.mobiservice.dev.utils.extensions.*
import uz.mobiuz.mobiservice.dev.utils.hideKeyboard
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import uz.mobiuz.mobiservice.dev.LanguageActivity

@AndroidEntryPoint
class CheckPhoneFragment : BaseFragment(R.layout.fragment_check_phone) {

    private var _bn: FragmentCheckPhoneBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private val navController: NavController by lazy(LazyThreadSafetyMode.NONE) { NavHostFragment.findNavController(this) }
    var phone = ""
    var phoneRaw = ""
    var oldText = ""
    var newText = ""

    private val viewModel: AuthViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentCheckPhoneBinding.bind(view)

        setUpUI()
        collects()


    }

    override fun setUpUI() {
        bn.apply {


            toolbar.setNavigationOnClickListener {
                requireActivity().onBackPressed()
                startActivity(Intent(requireContext(),LanguageActivity::class.java))
            }

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

            inputPhone.addTextChangedListener(object : TextWatcherWrapper() {
                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                    super.beforeTextChanged(s, start, count, after)
                    oldText = s.toString()
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    try {
                        inputPhone.removeTextChangedListener(this)
                        val text = s.toString()
                        if(text.length < 5){
                            inputPhone.setText("+998 ")
                            inputPhone.setSelection(5)
                        }else{
                            newText = text.filter { it.isDigit() || it == '+'}.maskedTextMobi()
                            inputPhone.setText(newText)
                            inputPhone.setSelection(oldText.checkChangedPosition(newText))

                        }
                        inputPhone.addTextChangedListener(this)
                        btnCheckPhone.isEnabled = inputPhone.text.toString().filter { it.isDigit() || it == '+' }.length == 13
                    }catch (e: Exception){
                        inputPhone.text.clear()
                        inputPhone.addTextChangedListener(this)
                    }

                }
            })

            btnCheckPhone.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    phone = inputPhone.text.toString().filter { it.isDigit() || it == '+' }
                    phoneRaw = inputPhone.text.toString().trim()
                    when {
                        phone.length < 13 -> {
                            inputPhone.startAnimation(AnimationUtils.loadAnimation(requireContext(), R.anim.shake))
                        }
                        else ->{
                            if(checkInternet()){
                                viewModel.checkPhone(UserAuth(phone.replace("+", "")))
                            }
                        }
                    }

                }
            })

        }
    }

    override fun collects() {
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.checkPhoneUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        if (it.data.action == CONSTANTS.REGISTER) {
                            navController.navigate(R.id.registerFragment, bundleOf(CONSTANTS.PHONE to phone), Utils.navOptions())
                        } else {
                            navController.navigate(R.id.loginFragment, bundleOf(CONSTANTS.PHONE to phoneRaw), Utils.navOptions())
                        }
                        showProgressDialog(false)
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        showToastMessage(it.message)
                    }

                    is UiStateObject.LOADING -> {
                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }
    }

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