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

import android.content.Intent
import android.net.Uri
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 uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.databinding.FragmentRegisterBinding
import uz.mobiuz.mobiservice.dev.model.SharedPref
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.getColorCompat
import uz.mobiuz.mobiservice.dev.utils.extensions.makeLinks
import uz.mobiuz.mobiservice.dev.utils.extensions.showCustomDialog
import uz.mobiuz.mobiservice.dev.utils.hideKeyboard
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import javax.inject.Inject

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

    @Inject
    lateinit var pref: SharedPref
    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 password = ""
    private var confirmPassword = ""
    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 {

            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }

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

            txtHelperMobiuz.makeLinks(
                Pair(CONSTANTS.HTTP_MOBI_UZ, View.OnClickListener {
                    val uri = Uri.parse(CONSTANTS.HTTP_MOBI_UZ)
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.data = uri
                    startActivity(intent)
                })
            )

            txtAgree.makeLinks(
                Pair(getString(R.string.terms_of_use), View.OnClickListener {

                    val uri = Uri.parse(
                        when (pref.language) {
                            CONSTANTS.UZ -> CONSTANTS.LICENSE_UZ
                            CONSTANTS.RU -> CONSTANTS.LICENSE_RU
                            else -> CONSTANTS.LICENSE_EN
                        }
                    )
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.data = uri
                    startActivity(intent)
                }),

                Pair(getString(R.string.privacy_policy), View.OnClickListener {
                    val uri = Uri.parse(
                        when (pref.language) {
                            CONSTANTS.UZ -> CONSTANTS.PRIVACY_POLICY_UZ
                            CONSTANTS.RU -> CONSTANTS.PRIVACY_POLICY_RU
                            else -> CONSTANTS.PRIVACY_POLICY_EN
                        }
                    )
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.data = uri
                    startActivity(intent)
                }),
            )


            txtEnterPhone.text = if (type == CONSTANTS.TYPE_FORGET) getString(R.string.think_password) else getString(R.string.register)
            inputPassword.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    checkPasswordAndConfirm()

                }
            })

            inputConfirm.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    checkPasswordAndConfirm()
                }
            })


            btnRegister.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    password = inputPassword.text.toString().trim()
                    confirmPassword = inputConfirm.text.toString().trim()
                    if(password == confirmPassword){
                        if(checkInternet()){
                            if (type == CONSTANTS.TYPE_FORGET) {
                                viewModel.resetPassword(UserAuth(phone.filter { it.isDigit() }, password, code))
                            } else {
                                viewModel.register(UserAuth(phone.filter { it.isDigit() }, password))
                            }
                        }

                    }

                }
            })


        }
    }

    private fun checkPasswordAndConfirm(){
        bn.apply {
            password = inputPassword.text.toString().trim()
            confirmPassword = inputConfirm.text.toString().trim()
            btnRegister.isEnabled = (password.length > 3) && (password == confirmPassword)
            txtCheckPassword.isVisible = password.length < 4
            if (password.isNotEmpty() && confirmPassword.isNotEmpty()){
                if (password == confirmPassword){
                    imageCheck.setImageResource(R.drawable.ic_baseline_check_circle)
                    txtCheckConfirm.text = getString(R.string.password_same)
                    txtCheckConfirm.setTextColor(getColorCompat(R.color.green100))

                }else{
                    imageCheck.setImageResource(R.drawable.ic_vector_error)
                    txtCheckConfirm.text = getString(R.string.password_not_same)
                    txtCheckConfirm.setTextColor(getColorCompat(R.color.primary100))
                }
                imageCheck.isVisible = true
                txtCheckConfirm.isVisible = true
            }
        }

    }

    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, CONSTANTS.PIN_CODE to it.data),
                            Utils.navOptions()
                        )
                    }
                    is UiStateObject.ERROR -> {
                        code = ""
                        showProgressDialog(false)
                        showToastMessage(it.message)
                    }

                    is UiStateObject.LOADING -> {
                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.resetPasswordUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        showCustomDialog(getString(R.string.password_successfully_updated),true){
                            navController.popBackStack(R.id.loginFragment, false)
                            navController.navigate(R.id.installPinFragment, bundleOf(CONSTANTS.TYPE_PIN to CONSTANTS.NEW_PIN), Utils.navOptions())
                        }
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        showToastMessage(it.message)
                    }

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

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