package com.mobiuz.app.dev.ui.auth.verification

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.animation.AnimationUtils
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.FragmentVerificationBinding
import com.mobiuz.app.dev.model.SharedPref
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.hideKeyboard
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import javax.inject.Inject

@AndroidEntryPoint
class VerificationFragment : BaseFragment(R.layout.fragment_verification) {

    @Inject
    lateinit var pref: SharedPref

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


    private var phone = ""
    private var type = ""

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentVerificationBinding.bind(view)
        setUpUI()
        count(true)
        collects()
    }

    override fun setUpUI() {
        bn.apply {

            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }

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

            lineField.addTextChangedListener(object : TextWatcherWrapper() {
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    super.onTextChanged(s, start, before, count)
                    bn.lineField.setTextColor(Color.RED)
                    btnLogin.isEnabled = (s.toString().length == 6)
                }
            })


            btnLogin.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    getLinePinCodes()
                    val auth = UserAuth(phone.replace("+", "").replace(" ", ""), null, code)
                    if (type == CONSTANTS.TYPE_FORGET) {
                        viewModel.checkResetCode(auth)
                    } else {
                        viewModel.verification(auth)
                    }

                }
            })

            sentCodeAgain.setOnClickListener {
                count(true)
            }
            coutdownView.setOnCountdownEndListener {
                count(false)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        bn.lineField.hideKeyboard()
    }

    private fun getLinePinCodes() {
        code = bn.lineField.text.toString()
    }

    override fun collects() {
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.verificationUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        pref.userPhone = phone
                        navController.navigate(R.id.pinFragment, null, Utils.navOptions())
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        bn.lineField.setTextColor(Color.RED)
                        bn.lineField.startAnimation(AnimationUtils.loadAnimation(requireContext(), R.anim.shake))
                        showToastMessage(it.message)
                    }

                    is UiStateObject.LOADING -> {
                        showProgressDialog(true)
                    }
                    else -> Unit
                }
            }
        }
        viewLifecycleOwner.lifecycleScope.launchWhenStarted {
            viewModel.checkResetCodeUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        showProgressDialog(false)
                        pref.userPhone = phone
                        navController.navigate(
                            R.id.registerFragment,
                            bundleOf(
                                CONSTANTS.PHONE to phone,
                                CONSTANTS.TYPE_VERIFICATION to CONSTANTS.TYPE_FORGET,
                                CONSTANTS.PIN_CODE to code,
                            ),
                            Utils.navOptions()
                        )
                    }
                    is UiStateObject.ERROR -> {
                        showProgressDialog(false)
                        bn.lineField.setTextColor(Color.RED)
                        bn.lineField.startAnimation(AnimationUtils.loadAnimation(requireContext(), R.anim.shake))
                        showToastMessage(it.message)
                    }

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

    private fun count(status: Boolean) {
        bn.apply {
            countWaitText.hideKeyboard()
            sentCodeAgain.isVisible = !status
            coutdownViewHelperText.isVisible = !status
            coutdownView.isVisible = status
            if (status) coutdownView.start(60000)
        }
    }

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

}
