package com.mobiuz.app.dev

import android.content.BroadcastReceiver
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
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 com.google.gson.Gson
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.LocaleHelper
import com.mobiuz.app.dev.utils.extensions.*
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
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 lateinit var mFirebaseAnalytics: FirebaseAnalytics

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

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

        FirebaseMessaging.getInstance().token.addOnCompleteListener {
            if (it.isSuccessful) pref.setDeviceToken(it.result.toString())
        }
        if (savedInstanceState == null) {
            setupBottomNavigationBar()
        }

        setUpUI()
        collects()


//       receiver = object : BroadcastReceiver(){
//            override fun onReceive(context: Context?, intent: Intent?) {
//               val type = NetworkUtil.getConnectivityStatus(this@MainActivity)
//                if (type == 0){
//                    showMessage("Internet o'chdi")
//                }else{
//                    showMessage("Internet yondi")
//                }
////                customLog("onReceive=${type}")
//            }
//        }
////        val receiver = NetworkChangeReceiver()
//        val intentFilter = IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")
//        registerReceiver(receiver,intentFilter)

    }


    private fun setUpUI() {

        bn.apply {

            header.txtUserPhone.text = pref.userPhone.customMasketHome()
            customLog("lang:${pref.language}")
            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()
                        }
//                        uz.agr.sdk.open_source.ui.MainFormFragment
                        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.safetyFragment)
                }
            })

            header.headerLayout.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navigateToSettingsScreen(R.id.profileFragment)
                }
            })
            txtRedactData.setOnClickListener {
                navigateUri("https://www.mobi.uz/")
            }

            txtPublicOferta.setOnClickListener {
                navigateUri("https://www.mobi.uz/")
            }
            txtConfidensialnost.setOnClickListener {
                navigateUri("https://www.mobi.uz/")
            }
        }
    }

    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()
        bn.drawerLayout.closeDrawer(GravityCompat.START)
    }


    override fun onResume() {
        super.onResume()

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

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

    private fun navigateToSettingsScreen(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 -> {
                        customLog("bottomSheetUiState ${it.data}")
                        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 -> {
                        customLog("locked:${it.data}")
                       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_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
//        unregisterReceiver(receiver)
        super.onDestroy()
    }
}