package uz.ssd.mobiuz.ui.auth.check

import android.os.Bundle
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 dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import uz.ssd.mobiuz.R
import uz.ssd.mobiuz.databinding.FragmentCheckPhoneBinding
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.ui.global.ButtonClick
import uz.ssd.mobiuz.ui.global.CONSTANTS
import uz.ssd.mobiuz.utils.Utils
import uz.ssd.mobiuz.utils.extensions.customLog
import uz.ssd.mobiuz.utils.extensions.showCustomDialog

@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 = ""

    private val viewModel: AuthViewModel by viewModels()

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

        setUpUI()
        collects()

    }

    override fun setUpUI() {
        bn.apply {

            inputPhone.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    customLog("s=${s?.toString()?.length}")
                    bn.helperPhone.isVisible = false
                    btnLogin.isEnabled = inputPhone.text.toString().trim().length == 17
                }
            })

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

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

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

                    is UiStateObject.ERRORS -> {
                        it.errors.forEach {
                            if(it.key == "phone"){
                                bn.layoutInput.startAnimation(AnimationUtils.loadAnimation(requireContext(),R.anim.shake))
                                bn.helperPhone.isVisible = true
                                bn.helperPhone.text = it.message
                            }
                        }
                        showProgressDialog(false)

                    }
                    is UiStateObject.LOADING -> {
                        bn.helperPhone.isVisible = false
                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }
    }

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