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

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.provider.Settings.ACTION_BIOMETRIC_ENROLL
import android.view.View
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricManager.Authenticators.*
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.mobiuz.app.R
import com.mobiuz.app.databinding.FragmentSecurityBinding
import com.mobiuz.app.dev.model.SharedPref
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.utils.Utils
import com.mobiuz.app.dev.utils.extensions.showMessage
import dagger.hilt.android.AndroidEntryPoint

import javax.inject.Inject

@AndroidEntryPoint
class SecurityFragment : BaseFragment(R.layout.fragment_security) {

    @Inject
    lateinit var pref: SharedPref

    private lateinit var biometricManager: BiometricManager

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


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = FragmentSecurityBinding.bind(view)
        setUpUI()
        collects()
        biometricManager = BiometricManager.from(requireContext())
        checkBiometricAfter(false)

    }

    override fun setUpUI() {
        bn.apply {

            toolbar.setNavigationOnClickListener {
                navController.navigateUp()
            }
            val text = getString(R.string.settings_safety)
            val myText = text.replace(CONSTANTS.DEFAULT_PHONE, pref.userPhone)
            txtPhoneSafety.text = myText
            switchBiometria.isChecked = pref.isUseFingerPrint

            switchBiometria.setOnCheckedChangeListener { _, isChecked ->

                if(isChecked && checkBiometric()){
                    showToastMessage(getString(R.string.biometric_enabled))
                    pref.isUseFingerPrint = true
                }else{
                    if(checkBiometric()){
                        pref.isUseFingerPrint = false
                        showToastMessage(getString(R.string.biometric_disabled))
                    }else{
                        checkBiometricAfter(true)
                    }
                }

                switchBiometria.isChecked = checkBiometric() && isChecked


            }
            btnBiometric.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    switchBiometria.isChecked = !switchBiometria.isChecked
                }
            })


            btnChangePin.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navController.navigate(R.id.installPinFragment, bundleOf(CONSTANTS.TYPE_PIN to CONSTANTS.CURRENT_PIN), Utils.navOptions())
                }
            })
            btnChangePassword.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navController.navigate(R.id.changePasswordFragment, bundleOf(CONSTANTS.TYPE_PASSWORD to CONSTANTS.CURRENT_PASSWORD), Utils.navOptions())
                }
            })
        }
    }

    private fun checkBiometricAfter(toSettings:Boolean) {
        when (biometricManager.canAuthenticate(BIOMETRIC_STRONG  or BIOMETRIC_WEAK)) {
            BiometricManager.BIOMETRIC_SUCCESS -> {
                bn.btnBiometric.isVisible = true
            }

            BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> {
                pref.isUseFingerPrint = false
                bn.btnBiometric.isVisible = false
            }

            BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {

                if (toSettings){
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
                        val enrollIntent = Intent(ACTION_BIOMETRIC_ENROLL).apply {
                            putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED, BIOMETRIC_STRONG or BIOMETRIC_WEAK)
                        }
                        pref.isShowPin = false
                        startActivityForResult(enrollIntent, 1)
                    }else{
                        showMessage(getString(R.string.to_settings))
                    }
                }

                pref.isUseFingerPrint = false
            }

            else -> {
                if (toSettings) showMessage(getString(R.string.to_settings))
            }
        }
    }


    private fun checkBiometric(): Boolean {
        return when (biometricManager.canAuthenticate(BIOMETRIC_STRONG or BIOMETRIC_WEAK)) {
            BiometricManager.BIOMETRIC_SUCCESS -> true
            else -> false
        }
    }


    override fun collects() {}

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