package uz.ssd.mobiuz.ui.auth.register

import android.os.Bundle
import android.view.View
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.FragmentRegisterBinding
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.ButtonClick
import uz.ssd.mobiuz.ui.global.CONSTANTS
import uz.ssd.mobiuz.ui.global.TextWatcherWrapper
import uz.ssd.mobiuz.utils.Utils
import uz.ssd.mobiuz.utils.extensions.showCustomDialog

@AndroidEntryPoint
class RegisterFragment : BaseFragment(R.layout.fragment_register) {

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

    private val viewModel: AuthViewModel by viewModels()
    private var phone = ""
    private var type = ""
    private var code = ""

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

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

        setUpUI()
        collects()
    }

    override fun setUpUI() {
        bn.apply {
            inputPassword.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    txtCheckPassword.isVisible = (s.toString().length < 5)
                    val confirmText = inputConfirm.text.toString().trim()
                    if (confirmText.isNotEmpty()) {
                        if (s.toString() == confirmText) {
                            imageCheck.setImageResource(R.drawable.ic_baseline_check_circle)
                            txtCheckConfirm.text = getString(R.string.password_same)
                            txtCheckConfirm.setTextColor(requireActivity().resources.getColor(R.color.green))
                            btnLogin.isEnabled = true
                        } else {
                            imageCheck.setImageResource(R.drawable.ic_vector_error)
                            txtCheckConfirm.text = getString(R.string.password_not_same)
                            btnLogin.isEnabled = false
                            txtCheckConfirm.setTextColor(requireActivity().resources.getColor(R.color.red))
                        }
                        imageCheck.isVisible = true
                        txtCheckConfirm.isVisible = true
                    } else {
                        imageCheck.isVisible = false
                        txtCheckConfirm.isVisible = false
                    }

                }
            })

            inputConfirm.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    if (s.toString() == inputPassword.text.toString().trim()) {
                        imageCheck.setImageResource(R.drawable.ic_baseline_check_circle)
                        txtCheckConfirm.text = getString(R.string.password_same)
                        txtCheckConfirm.setTextColor(requireActivity().resources.getColor(R.color.green))
                        btnLogin.isEnabled = true
                    } else {
                        imageCheck.setImageResource(R.drawable.ic_vector_error)
                        txtCheckConfirm.text = getString(R.string.password_not_same)
                        btnLogin.isEnabled = false
                        txtCheckConfirm.setTextColor(requireActivity().resources.getColor(R.color.red))
                    }
                    imageCheck.isVisible = true
                    txtCheckConfirm.isVisible = true
                }
            })


            btnLogin.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    val password = inputPassword.text.toString().trim()
                    val confirm = inputConfirm.text.toString().trim()
                    when {
                        password.length < 5 || password != confirm -> {

                        }
                        else -> {
                            if (type == CONSTANTS.TYPE_FORGET) {
                                viewModel.resetPassword(UserAuth(phone.replace(" ", "").replace("+", ""), password,code))
                            } else {
                                viewModel.register(UserAuth(phone.replace(" ", "").replace("+", ""), password))
                            }

                        }
                    }

                }
            })

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

    override fun collects() {
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.registerUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        navController.navigate(R.id.verificationFragment, bundleOf(CONSTANTS.PHONE to phone), Utils.navOptions())
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        showCustomDialog(it.message, false) {}
                    }

                    is UiStateObject.ERRORS -> {
                        showProgressDialog(false)
                        var message = ""
                        it.errors.forEach {
                            message += it.message
                        }
//                        97 756 5078
                        showCustomDialog(message, false) {}
                    }
                    is UiStateObject.LOADING -> {
                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.resetPasswordUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        showCustomDialog("Password successfully updated", true) {
                            navController.popBackStack()
                            navController.navigate(R.id.pinFragment,null,Utils.navOptions())
                        }

                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        showCustomDialog(it.message, false) {}
                    }

                    is UiStateObject.ERRORS -> {
                        showProgressDialog(false)
                        var message = ""
                        it.errors.forEach {
                            message += it.message
                        }
//                        97 756 5078
                        showCustomDialog(message, false) {}
                    }
                    is UiStateObject.LOADING -> {
                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }
    }

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