package com.mobiuz.app.dev.ui.settings.safety.password

import android.content.Intent
import android.graphics.Color
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 com.mobiuz.app.R
import com.mobiuz.app.databinding.FragmentChangePasswordBinding
import com.mobiuz.app.dev.MainViewModel
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.model.UserAuth
import com.mobiuz.app.dev.network.model.ChangePassword
import com.mobiuz.app.dev.network.model.UiStateObject
import com.mobiuz.app.dev.ui.auth.AuthActivity
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.customLog
import com.mobiuz.app.dev.utils.extensions.getColorCompat
import com.mobiuz.app.dev.utils.extensions.showCustomDialog
import com.mobiuz.app.dev.utils.extensions.showMessage
import com.mobiuz.app.dev.utils.hideKeyboard
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import javax.inject.Inject

@AndroidEntryPoint
class ChangePasswordFragment : BaseFragment(R.layout.fragment_change_password) {

    @Inject
    lateinit var pref: SharedPref
    private var _bn: FragmentChangePasswordBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private val navController: NavController by lazy(LazyThreadSafetyMode.NONE) { NavHostFragment.findNavController(this) }
    private var type = ""
    private var count = 3
    private lateinit var decorView: View
    private var oldPassword = ""
    private var newPassword = ""

    private val viewModel: AuthViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            oldPassword = it.getString(CONSTANTS.OLD_PASSWORD, "") ?: ""
            newPassword = it.getString(CONSTANTS.LATEST_PASSWORD, "") ?: ""
            type = it.getString(CONSTANTS.TYPE_PASSWORD, "") ?: ""
        }
    }

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

        setUpUI()
        collects()
    }

    override fun setUpUI() {
        bn.apply {


            val text = when (type) {
                CONSTANTS.CURRENT_PASSWORD ->{
                    txtForgetPassword.isVisible = true
                    getString(R.string.enter_current_password)
                }
                CONSTANTS.NEW_PASSWORD -> {
                    getString(R.string.enter_new_password)
                }
                else -> {
                    getString(R.string.enter_confirm_new_password)
                }
            }
            txtPassword.text = text

            viewGroup.setOnClickListener(object : ButtonClick(){
                override fun onSingleClick(v: View?) {
                    bn.viewGroup.hideKeyboard()
                }
            })

            txtForgetPassword.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    if(type == CONSTANTS.CURRENT_PASSWORD){
                        viewModel.forgetPassword(UserAuth(pref.userPhone.replace(" ", "").replace("+", "")))
                    }
                }
            })

            inputPassword.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    if(type == CONSTANTS.CONFIRM_NEW_PASSWORD){

                        if (s.toString() == newPassword) {
                            imageCheck.setImageResource(R.drawable.ic_baseline_check_circle)
                            txtCheckConfirm.text = getString(R.string.password_same)
                            txtCheckConfirm.setTextColor(getColorCompat(R.color.green100))
                            btnLogin.isEnabled = true
                        } else {
                            imageCheck.setImageResource(R.drawable.ic_vector_error)
                            txtCheckConfirm.text = getString(R.string.password_not_same)
                            btnLogin.isEnabled = false
                            txtCheckConfirm.setTextColor(getColorCompat(R.color.primary100))
                        }
                        imageCheck.isVisible = true
                        txtCheckConfirm.isVisible = true
                    }else{
                        loadError(false)
                        btnLogin.isEnabled = s.toString().length > 3
                        imageCheck.isVisible = false
                        txtCheckConfirm.isVisible = false
                    }

                }
            })



            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 -> {
                            bn.btnLogin.hideKeyboard()
                            when (type) {
                                CONSTANTS.CURRENT_PASSWORD -> {
                                    oldPassword = password
                                    viewModel.checkPassword(UserAuth(password = oldPassword))
                                }

                                CONSTANTS.NEW_PASSWORD -> {

                                    navController.navigate(
                                        R.id.currentPasswordFragment,
                                        bundleOf(
                                            CONSTANTS.TYPE_PASSWORD to CONSTANTS.CONFIRM_NEW_PASSWORD,
                                            CONSTANTS.OLD_PASSWORD to oldPassword,
                                            CONSTANTS.LATEST_PASSWORD to password,

                                            ), Utils.navOptions()
                                    )
                                }

                                CONSTANTS.CONFIRM_NEW_PASSWORD -> {
                                    if (newPassword == password) {
                                        viewModel.changePassword(ChangePassword(oldPassword,newPassword))
                                    }
                                }
                            }
                        }
                    }

                }
            })

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


    private fun loadError(status:Boolean){
        bn.apply {
            if (count == 0){
                errorTitle.text = getString(R.string.impossible_change_password)
                errorText.text = getString(R.string.popitok_error_password)
            }else{
                errorText.text = getString(R.string.popitok,count.toString())
            }
            errorLayout.isVisible = status
            div.setBackgroundColor(if(status) getColorCompat(R.color.primary100) else Color.TRANSPARENT)
            decorView = requireActivity().window.decorView
            decorView.systemUiVisibility = if(status) View.VISIBLE else{decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR}
        }
    }

    override fun collects() {
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.checkPasswordUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        navController.navigate(
                            R.id.currentPasswordFragment,
                            bundleOf(
                                CONSTANTS.OLD_PASSWORD to oldPassword,
                                CONSTANTS.TYPE_PASSWORD to CONSTANTS.NEW_PASSWORD
                            ),
                            Utils.navOptions()
                        )

                        showProgressDialog(false)
                    }
                    is UiStateObject.ERROR -> {
                        if(it.message == "Invalid password"){
                            count--
                            if(count == 0){
                                loadError(true)
                                showCustomDialog(getString(R.string.impossible_change_password), false){
                                    pref.clearUserData()
                                    val intent = Intent(requireContext(), AuthActivity::class.java)
                                    intent.putExtra(CONSTANTS.TYPE_AUTH, CONSTANTS.LOGIN)
                                    intent.putExtra(CONSTANTS.PHONE, pref.userPhone)
                                    startActivity(intent)
                                    requireActivity().finish()
                                }

                            }else{
                                loadError(true)
                            }
                        }else{
                            showToastMessage(it.message)
                        }

                        showProgressDialog(false)

                    }

                    is UiStateObject.LOADING -> {
                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.changePasswordUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        showCustomDialog(getString(R.string.password_updated),true){
                            navController.popBackStack(R.id.safetyFragment, false)
                        }
                    }
                    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 -> {
                        requireActivity().finish()
                        pref.clearUserData()
                        val intent = Intent(requireContext(), AuthActivity::class.java)
                        intent.putExtra(CONSTANTS.TYPE_AUTH, CONSTANTS.TYPE_VERIFICATION)
                        intent.putExtra(CONSTANTS.PHONE, pref.userPhone)
                        startActivity(intent)
                        showProgressDialog(false)
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        showToastMessage(it.message)
                    }

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

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