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

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.google.firebase.FirebaseApp
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.messaging.FirebaseMessaging
import com.mobiuz.app.R
import com.mobiuz.app.databinding.ActivityAuthBinding
import com.mobiuz.app.dev.MainActivity
import com.mobiuz.app.dev.OfflineActivity
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.ui.global.CONSTANTS
import com.mobiuz.app.dev.utils.NetworkUtil
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 AuthActivity : AppCompatActivity() {

    @Inject
    lateinit var pref: SharedPref

    private var _bn: ActivityAuthBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")
    private lateinit var navController: NavController
    private lateinit var mFirebaseAnalytics: FirebaseAnalytics
    private lateinit var receiver: BroadcastReceiver
    private var type = 0
    private var verificationCode: String? = null
    private var phone = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _bn = ActivityAuthBinding.inflate(layoutInflater)
        setContentView(bn.root)
        val fragment = supportFragmentManager.findFragmentById(R.id.auth_container) as NavHostFragment
        navController = NavHostFragment.findNavController(fragment)
        FirebaseApp.initializeApp(this)
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this)
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

        FirebaseMessaging.getInstance().token.addOnCompleteListener {
            if (it.isSuccessful) pref.deviceToken = it.result.toString()
        }
        window.decorView.systemUiVisibility = window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

        intent?.let {
            phone = it.getStringExtra(CONSTANTS.PHONE) ?: ""
            verificationCode = it.getStringExtra(CONSTANTS.PIN_CODE)

            when (it.getStringExtra(CONSTANTS.TYPE_AUTH)) {
                CONSTANTS.PIN_CODE -> {
                    navController.popBackStack()
                    navController.navigate(R.id.pinFragment, bundleOf(CONSTANTS.TYPE_PIN to CONSTANTS.NEW_PIN), Utils.navOptions())
                }
                CONSTANTS.LOGIN -> {
                    navController.popBackStack()
                    navController.navigate(R.id.loginFragment, bundleOf(CONSTANTS.PHONE to pref.userPhone), Utils.navOptions())
                }
                CONSTANTS.TYPE_VERIFICATION -> {
                    navController.popBackStack()
                    navController.navigate(R.id.myVerificationFragment, bundleOf(CONSTANTS.PHONE to phone , CONSTANTS.PIN_CODE to verificationCode), Utils.navOptions())
                }
            }
        }
        bn.btnTryAgain.setOnClickListener {
            if (type == 0){
                navigate()
            }
        }

        receiver = object : BroadcastReceiver(){
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent?.action == CONSTANTS.CONNECTIVITY_CHANGE){
                    sendBroadcast(Intent(CONSTANTS.MY_CONNECTIVITY_CHANGE))
                }
                if (intent?.action == CONSTANTS.MY_CONNECTIVITY_CHANGE){
                    type = NetworkUtil.getConnectivityStatus(this@AuthActivity)
                    bn.btnTryAgain.isVisible = (type == 0)
                            && (navController.currentDestination?.id != R.id.pinFragment)
                            && (navController.currentDestination?.id != R.id.biometricFragment)
                    if(type == 0){
                        showMessage(getString(R.string.not_internet_connect))
                    }
                }
            }
        }
        val intentFilter = IntentFilter()
        intentFilter.addAction(CONSTANTS.CONNECTIVITY_CHANGE)
        intentFilter.addAction(CONSTANTS.MY_CONNECTIVITY_CHANGE)
        registerReceiver(receiver,intentFilter)
    }

    fun navigate(){
        val intent = Intent(this, OfflineActivity::class.java)
        intent.putExtra(CONSTANTS.TYPE_SERVICE, CONSTANTS.FROM_ONLINE)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
        startActivity(intent)
        finish()
    }

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