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

import android.content.Intent
import android.net.Uri
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 uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.databinding.FragmentLoginBinding
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.checkInternet
import uz.mobiuz.mobiservice.dev.utils.extensions.makeLinks
import uz.mobiuz.mobiservice.dev.utils.hideKeyboard
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect

@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 {

            viewGroup.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    bn.viewGroup.hideKeyboard()
                }
            })
            txtHelperMobiuz.makeLinks(Pair(CONSTANTS.WWW_MOBI_UZ, View.OnClickListener {
                val uri = Uri.parse(CONSTANTS.MOBI_UZ_SELF_CARE)
                val intent = Intent(Intent.ACTION_VIEW)
                intent.data = uri
                startActivity(intent)
            }))
            inputPhone.setText(phone)

            txtForgetPassword.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    viewModel.forgetPassword(UserAuth(phone.filter { it.isDigit() }))
                }
            })

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



            btnLogin.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    val password = inputPassword.text.toString().trim()
                    when {
                        password.length < 4 -> {
                            inputPassword.startAnimation(
                                android.view.animation.AnimationUtils.loadAnimation(
                                    requireContext(),
                                    R.anim.shake
                                )
                            )
                        }
                        else -> {
                            if (checkInternet()) {
                                viewModel.login(UserAuth(phone.filter { it.isDigit() }, 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,
                            bundleOf(CONSTANTS.PHONE to phone, CONSTANTS.PIN_CODE to it.data),
                            Utils.navOptions()
                        )
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        showToastMessage(it.message)
                    }

                    is UiStateObject.LOADING -> {
                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.forgetPasswordUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        navController.navigate(
                            R.id.verificationFragment,
                            bundleOf(
                                CONSTANTS.PHONE to phone,
                                CONSTANTS.TYPE_VERIFICATION to CONSTANTS.TYPE_FORGET,
                                CONSTANTS.PIN_CODE to it.data
                            ),
                            Utils.navOptions()
                        )
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        showToastMessage(it.message)
                    }

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

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