package com.mobiuz.app.dev

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
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 com.mobiuz.app.R
import com.mobiuz.app.databinding.ActivityMainBinding
import com.mobiuz.app.dev.model.SharedPref
import com.mobiuz.app.dev.network.model.UiStateObject
import com.mobiuz.app.dev.ui.auth.AuthActivity
import com.mobiuz.app.dev.ui.global.ButtonClick
import com.mobiuz.app.dev.ui.global.CONSTANTS
import com.mobiuz.app.dev.ui.global.FullScreenDialog
import com.mobiuz.app.dev.ui.settings.SettingsActivity
import com.mobiuz.app.dev.utils.extensions.setupWithNavController
import com.mobiuz.app.dev.utils.extensions.showCustomExitDialog
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
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 mFirebaseAnalytics: FirebaseAnalytics

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _bn = ActivityMainBinding.inflate(layoutInflater)
        setContentView(bn.root)

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

//        Firebase.messaging.subscribeToTopic("just").addOnCompleteListener { task ->
//            Log.e("AAA", "subscribe: ${task.isSuccessful}")
//        }
        FirebaseMessaging.getInstance().token.addOnCompleteListener {
            if (it.isSuccessful) pref.setDeviceToken(it.result.toString())
        }
        if (savedInstanceState == null) {
            setupBottomNavigationBar()
        }

        setUpUI()
        collects()

        showPinCode()
    }

    private fun showPinCode() {
        intent?.let {
            val arg = it.getStringExtra(CONSTANTS.FIRST) ?: ""
            if (arg.isEmpty()) {
                val dialog = FullScreenDialog()
                dialog.setOnPinDoneListener {
                    finishAffinity()
                    pref.clearUserData()
                    val intent = Intent(this, AuthActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                    startActivity(intent)
                }
                dialog.show(supportFragmentManager, "tag")
            }
        }
    }

    private fun setUpUI() {

        bn.apply {

            header.txtUserPhone.text = pref.userPhone
            txtLanguage.text = pref.language
            btnExit.setOnClickListener(object : ButtonClick(){
                override fun onSingleClick(v: View?) {
                    showCustomExitDialog {
                        pref.clearUserData()
                        val intent = Intent(this@MainActivity, AuthActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                        startActivity(intent)
                        finish()
                        bn.drawerLayout.closeDrawer(GravityCompat.START)
                    }
                }
            })

            btnLanguage.setOnClickListener(object :ButtonClick(){
                override fun onSingleClick(v: View?) {
                    val intent = Intent(this@MainActivity, SettingsActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                    startActivity(intent)
                    bn.drawerLayout.closeDrawer(GravityCompat.START)
                }
            })

            btnSupport.setOnClickListener(object : ButtonClick(){
                override fun onSingleClick(v: View?) {
                    val intent = Intent(this@MainActivity, SettingsActivity::class.java)
                    intent.putExtra(CONSTANTS.TYPE_SETTINGS, CONSTANTS.SUPPORT)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                    startActivity(intent)
                    bn.drawerLayout.closeDrawer(GravityCompat.START)
                }
            })

            btnSafety.setOnClickListener(object : ButtonClick(){
                override fun onSingleClick(v: View?) {
                    val intent = Intent(this@MainActivity, SettingsActivity::class.java)
                    intent.putExtra(CONSTANTS.TYPE_SETTINGS, CONSTANTS.SAFETY)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                    startActivity(intent)
                    bn.drawerLayout.closeDrawer(GravityCompat.START)
                }
            })

            header.headerLayout.setOnClickListener(object : ButtonClick(){
                override fun onSingleClick(v: View?) {
                    val intent = Intent(this@MainActivity, SettingsActivity::class.java)
                    intent.putExtra(CONSTANTS.TYPE_SETTINGS, CONSTANTS.PROFILE)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                    startActivity(intent)
                    bn.drawerLayout.closeDrawer(GravityCompat.START)
                }
            })
            txtRedactData.setOnClickListener {
//                bn.drawerLayout.closeDrawer(GravityCompat.START)
            }

            txtPublicOferta.setOnClickListener {
//                bn.drawerLayout.closeDrawer(GravityCompat.START)
            }
            txtConfidensialnost.setOnClickListener {
//                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.userNameUiState.collect {
                when (it) {
                    is UiStateObject.SUCCESS -> {
                        bn.header.txtUserName.text = it.data
                    }
                    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_profile
            )

            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
        super.onDestroy()
    }
}