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

import android.content.Intent
import android.os.Bundle
import android.util.Log
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.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.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 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{
                        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 -> {
                                    if(oldPassword == password){
                                        showMessage(getString(R.string.cannot_change_password))
                                    }else{
                                        navController.navigate(
                                            R.id.changePasswordFragment,
                                            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(){
        bn.apply {
            if (count == 0){
                showMessage( getString(R.string.popitok_error_password))
            }else{
                showMessage(getString(R.string.popitok_password,count.toString()))
            }
        }
    }

    override fun collects() {
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.checkPasswordUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        navController.navigate(
                            R.id.changePasswordFragment,
                            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){
                                showCustomDialog(getString(R.string.impossible_change_password), false){
                                    pref.clearUserData()
                                    val intent = Intent(requireContext(), AuthActivity::class.java)
                                    intent.putExtra(CONSTANTS.TYPE_AUTH, CONSTANTS.LOGIN)
                                    startActivity(intent)
                                    requireActivity().finish()
                                }
                            }else{
                                loadError()
                            }
                        }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)
                        intent.putExtra(CONSTANTS.PIN_CODE, it.data)
                        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()
    }
}