package com.mobiuz.app.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 com.mobiuz.app.R
import com.mobiuz.app.databinding.FragmentRegisterBinding
import com.mobiuz.app.dev.model.UserAuth
import com.mobiuz.app.dev.network.model.UiStateObject
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.makeLinks
import com.mobiuz.app.dev.utils.hideKeyboard
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect

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

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

            txtHelperMobiuz.makeLinks(
                Pair("www.mobi.uz", View.OnClickListener {
                val uri = Uri.parse("https://www.mobi.uz/")
                val intent = Intent(Intent.ACTION_VIEW)
                intent.data = uri
                startActivity(intent)
            }))

            txtAgree.makeLinks(
                Pair("Terms of Use", View.OnClickListener {
                    val uri = Uri.parse("https://www.mobi.uz/")
                    val intent = Intent(Intent.ACTION_VIEW)
                    intent.data = uri
                    startActivity(intent)
                }),

                Pair("Privacy Policy", View.OnClickListener {
                    val uri = Uri.parse("https://www.mobi.uz/")
                    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)
                    txtCheckPassword.isVisible = (s.toString().length < 4)
                    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.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(requireActivity().resources.getColor(R.color.primary100))
                        }
                        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.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(requireActivity().resources.getColor(R.color.primary100))
                    }
                    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 < 4 || 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.myVerificationFragment, bundleOf(CONSTANTS.PHONE to phone), Utils.navOptions())
                    }
                    is UiStateObject.ERROR -> {
                        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)
                        showToastMessage(getString(R.string.password_successfully_updated))
                        navController.popBackStack(R.id.loginFragment,false)
                        navController.navigate(R.id.pinFragment, null, Utils.navOptions())

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

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

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