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

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.os.bundleOf
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 uz.mobiuz.mobiservice.dev.OfflineActivity
import uz.mobiuz.mobiservice.dev.R
import uz.mobiuz.mobiservice.dev.databinding.ActivityAuthBinding
import uz.mobiuz.mobiservice.dev.model.SharedPref
import uz.mobiuz.mobiservice.dev.ui.global.CONSTANTS
import uz.mobiuz.mobiservice.dev.utils.LocaleHelper
import uz.mobiuz.mobiservice.dev.utils.Utils
import uz.mobiuz.mobiservice.dev.utils.extensions.showOfflineBottomSheetDialog
import dagger.hilt.android.AndroidEntryPoint
import uz.mobiuz.mobiservice.dev.utils.NetworkUtil
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 verificationCode: String? = null
    private val intentFilter = IntentFilter()
    private var phone = ""
    //    if offline type == 0
    private var type = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        LocaleHelper.setLocale(this)
        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()
        }

        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.verificationFragment, bundleOf(CONSTANTS.PHONE to phone , CONSTANTS.PIN_CODE to verificationCode), Utils.navOptions())
                }
            }
        }


        receiver = object : BroadcastReceiver(){
            override fun onReceive(context: Context?, intent: Intent?) {

                if (intent?.action == CONSTANTS.MY_CONNECTIVITY_CHANGE){
                        showOfflineBottomSheetDialog()
                }

                if (intent?.action == CONSTANTS.CONNECTIVITY_CHANGE){
                    type = NetworkUtil.getConnectivityStatus(this@AuthActivity)
                    if((type == 0) && (navController.currentDestination?.id != R.id.pinFragment)
                        && (navController.currentDestination?.id != R.id.biometricFragment))
                        showOfflineBottomSheetDialog()
                }
            }
        }

        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()
    }
}