package com.mobiuz.app.dev.ui.auth.check

import android.os.Bundle
import android.telephony.PhoneNumberFormattingTextWatcher
import android.text.Editable
import android.view.View
import android.view.animation.AnimationUtils
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.mobiuz.app.R
import com.mobiuz.app.databinding.FragmentCheckPhoneBinding
import com.mobiuz.app.dev.model.UserAuth
import com.mobiuz.app.dev.network.model.UiStateObject
import com.mobiuz.app.dev.ui.auth.AuthViewModel
import com.mobiuz.app.dev.ui.base.BaseFragment
import com.mobiuz.app.dev.ui.global.ButtonClick
import com.mobiuz.app.dev.ui.global.CONSTANTS
import com.mobiuz.app.dev.ui.global.TextWatcherWrapper
import com.mobiuz.app.dev.utils.Utils
import com.mobiuz.app.dev.utils.extensions.checkChangedPosition
import com.mobiuz.app.dev.utils.extensions.customLog
import com.mobiuz.app.dev.utils.extensions.maskedTextMobi
import com.mobiuz.app.dev.utils.extensions.showCustomDialog
import com.mobiuz.app.dev.utils.hideKeyboard
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect

@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 oldText = ""
    var newText = ""
    var phoneRaw = ""

    private val viewModel: AuthViewModel by viewModels()

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

        setUpUI()
        collects()

    }

    override fun setUpUI() {
        bn.apply {

            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)
                        newText = s.toString().replace(" ","").maskedTextMobi()
                        inputPhone.setText(newText)
                        inputPhone.setSelection(oldText.checkChangedPosition(newText))
                        inputPhone.addTextChangedListener(this)
                        btnLogin.isEnabled = inputPhone.text.toString().trim().length == 12
                    }catch (e: Exception){
                        inputPhone.text.clear()
                    }

                }
            })

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

                }
            })
            toolbar.setNavigationOnClickListener {
                requireActivity().finish()
            }
        }
    }

    override fun collects() {
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.checkPhoneUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        if (it.data.action == "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())
                        }
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        showToastMessage(it.message)
                    }

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

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