package uz.ssd.mobiuz.ui.auth

import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
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.FragmentLoginBinding
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.showMessage

@AndroidEntryPoint
class LoginFragment : BaseFragment(R.layout.fragment_login) {

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

    private val viewModel: AuthViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            phone = it.getString(CONSTANTS.PHONE, "")
        }
    }

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

        setUpUI()
        collects()
    }

    override fun setUpUI() {
        bn.apply {

            inputPhone.setText(phone)

            txtForgetPassword.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navController.navigate(R.id.forgetVerificationFragment, bundleOf(CONSTANTS.PHONE to phone), Utils.navOptions())
                }
            })

            inputPassword.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    btnLogin.isEnabled = (s.toString().length > 5)
                }
            })



            btnLogin.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    val password = inputPassword.text.toString().trim()
                    when {
                        password.length < 6 -> {
                            inputPassword.startAnimation(
                                android.view.animation.AnimationUtils.loadAnimation(
                                    requireContext(),
                                    R.anim.shake
                                )
                            )
                        }
                        else -> {
                            viewModel.login(UserAuth(phone.replace(" ", ""), password))
                        }
                    }

                }
            })

            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }
        }
    }

    override fun collects() {
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.loginUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        navController.navigate(R.id.verificationFragment, null, Utils.navOptions())
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        bn.inputPassword.startAnimation(
                            android.view.animation.AnimationUtils.loadAnimation(
                                requireContext(),
                                R.anim.shake
                            )
                        )
                        showMessage(it.message)
                    }
                    is UiStateObject.LOADING -> {
                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }
    }

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