package uz.mobiuz.mobiservice.dev

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.core.view.GravityCompat
import androidx.core.view.isVisible
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.LiveData
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.firebase.FirebaseApp
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.messaging.FirebaseMessaging
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import uz.mobiuz.mobiservice.dev.databinding.ActivityMainBinding
import uz.mobiuz.mobiservice.dev.model.SharedPref
import uz.mobiuz.mobiservice.dev.network.model.UiStateObject
import uz.mobiuz.mobiservice.dev.ui.auth.AuthActivity
import uz.mobiuz.mobiservice.dev.ui.global.ButtonClick
import uz.mobiuz.mobiservice.dev.ui.global.CONSTANTS
import uz.mobiuz.mobiservice.dev.utils.LocaleHelper
import uz.mobiuz.mobiservice.dev.utils.NetworkUtil
import uz.mobiuz.mobiservice.dev.utils.extensions.*
import javax.inject.Inject


@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    @Inject
    lateinit var pref: SharedPref

    private var _bn: ActivityMainBinding? = null
    private val bn get() = _bn ?: throw NullPointerException("cannot inflate")

    private lateinit var bottomNavigationView: BottomNavigationView
    private var currentNavController: LiveData<NavController>? = null
    private val viewModel: MainViewModel by viewModels()
    private lateinit var receiver: BroadcastReceiver
    private val intentFilter = IntentFilter()
    private var isFirstRunning = true

    // if offline type == 0
    private var type = 0

    private lateinit var mFirebaseAnalytics: FirebaseAnalytics

    override fun onCreate(savedInstanceState: Bundle?) {
        LocaleHelper.setLocale(this)
        super.onCreate(savedInstanceState)
        _bn = ActivityMainBinding.inflate(layoutInflater)
        setContentView(bn.root)
        pref.isShowPin = true

        if (savedInstanceState == null) {
            setupBottomNavigationBar()
        }

        val data = intent?.getStringExtra(CONSTANTS.FIRST)
        if (data != null && data == CONSTANTS.FIRST) {
            currentNavController?.value?.popBackStack()
            currentNavController?.value?.navigate(R.id.homeFragment)
        }

        FirebaseApp.initializeApp(this@MainActivity)
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this@MainActivity)

        FirebaseMessaging.getInstance().token.addOnCompleteListener {
            if (it.isSuccessful) pref.deviceToken = it.result.toString()
        }

        setUpUI()
        collects()

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

                if (intent?.action == CONSTANTS.UNAUTHORIZED) {
                    pref.clearUserData()
                    startActivity(Intent(this@MainActivity, AuthActivity::class.java))
                    finish()
                }
                if (intent?.action == CONSTANTS.CONNECTIVITY_CHANGE) {
                    sendBroadcast(Intent(CONSTANTS.MY_CONNECTIVITY_CHANGE))
                }
                if (intent?.action == CONSTANTS.MY_CONNECTIVITY_CHANGE) {
                    type = NetworkUtil.getConnectivityStatus(this@MainActivity)
                    if ((type == 0) && (currentNavController?.value?.currentDestination?.id != R.id.pinFragment)) {
                        showOfflineBottomSheetDialog()
                    }
                }
            }
        }

        intentFilter.addAction(CONSTANTS.CONNECTIVITY_CHANGE)
        intentFilter.addAction(CONSTANTS.UNAUTHORIZED)
        intentFilter.addAction(CONSTANTS.MY_CONNECTIVITY_CHANGE)
        registerReceiver(receiver, intentFilter)
    }




    private fun navigateUri(link: String) {
        val uri = Uri.parse(link)
        val intent = Intent(Intent.ACTION_VIEW)
        intent.data = uri
        startActivity(intent)
        pref.isShowPin = false
    }

    override fun onStop() {
        super.onStop()
        pref.blockedTime = System.currentTimeMillis()
        bn.drawerLayout.closeDrawer(GravityCompat.START)
    }


    override fun onResume() {
        super.onResume()

        customLog("main activity onResume")

        if (!isFirstRunning) {
            if (pref.isShowPin) {
                showPinCode()
            } else {
                pref.isShowPin = true
            }
        }
        isFirstRunning = false

    }

    private fun showPinCode() {
        if (pref.blockedTime < System.currentTimeMillis() - CONSTANTS.BLOCKED_TIME) {
            if (currentNavController?.value?.currentDestination?.id != R.id.pinFragment) {
                currentNavController?.value?.navigate(R.id.pinFragment, bundleOf(CONSTANTS.TYPE_PIN to CONSTANTS.TYPE_AFTER))
            }
        }
    }
    private fun setUpUI() {
        bn.apply {

            txtVersion.text = "v ${BuildConfig.VERSION_NAME}"
            header.txtUserPhone.text = pref.userPhone.customMasketHome()
            when (pref.language) {
                CONSTANTS.UZ -> txtLanguage.text = getString(R.string.uzbek)
                CONSTANTS.RU -> txtLanguage.text = getString(R.string.russian)
                CONSTANTS.EN -> txtLanguage.text = getString(R.string.english)
            }
            btnExit.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    showCustomExitDialog {
                        GlobalScope.launch {
                            viewModel.logOut()
                        }
                        val intent = Intent(this@MainActivity, AuthActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                        startActivity(intent)
                        pref.clearUserData()
                        finish()

                    }
                }
            })

            btnLanguage.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navigateToSettingsScreen(R.id.languageFragment)
                }
            })

            btnSupport.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navigateToSettingsScreen(R.id.supportFragment)
                }
            })

            btnSafety.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navigateToSettingsScreen(R.id.securityFragment)
                }
            })

            header.headerLayout.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navigateToSettingsScreen(R.id.profileFragment)
                }
            })
            txtLicenseAgreement.setOnClickListener {
                navigateUri(
                    when (pref.language) {
                        CONSTANTS.UZ -> CONSTANTS.LICENSE_UZ
                        CONSTANTS.RU -> CONSTANTS.LICENSE_RU
                        else -> CONSTANTS.LICENSE_EN
                    }
                )
            }

            txtPrivacyPolicy.setOnClickListener {
                navigateUri(
                    when (pref.language) {
                        CONSTANTS.UZ -> CONSTANTS.PRIVACY_POLICY_UZ
                        CONSTANTS.RU -> CONSTANTS.PRIVACY_POLICY_RU
                        else -> CONSTANTS.PRIVACY_POLICY_EN
                    }
                )
            }
        }
    }




    private fun navigateToSettingsScreen(@IdRes resId: Int) {
        val window = window.decorView
        window.systemUiVisibility = window.systemUiVisibility or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        currentNavController?.value?.navigate(resId)
        viewModel.bottomSheet(false)
        bn.drawerLayout.closeDrawer(GravityCompat.START)
    }

    private fun collects() {
        lifecycleScope.launchWhenStarted {
            viewModel.mainIndexUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        bn.drawerLayout.openDrawer(GravityCompat.START)
                    }
                    else -> Unit
                }
            }
        }

        lifecycleScope.launchWhenStarted {
            viewModel.bottomSheetUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        bn.bottomNavView.isVisible = it.data
                    }
                    else -> Unit
                }
            }
        }

        lifecycleScope.launchWhenStarted {
            viewModel.userNameUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        pref.userName = it.data
                        bn.header.txtUserName.text = it.data
                        bn.header.txtAvatar.text = it.data[0].toString()
                    }
                    else -> Unit
                }
            }
        }

        lifecycleScope.launchWhenStarted {
            viewModel.swipeDrawerUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        if (it.data) {
                            bn.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
                        } else {
                            bn.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
                        }
                    }
                    else -> Unit
                }
            }
        }

    }

    private fun setupBottomNavigationBar() {
        try {
            bottomNavigationView = findViewById(R.id.bottom_nav_view)
            val navGraphIds = listOf(
                R.navigation.nav_graph_home,
                R.navigation.nav_graph_services
            )

            val controller = bottomNavigationView.setupWithNavController(
                navGraphIds = navGraphIds,
                fragmentManager = supportFragmentManager,
                containerId = R.id.nav_host_fragment,
                intent = intent
            )
            currentNavController = controller
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        return currentNavController?.value?.navigateUp() ?: false
    }


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