package com.mobiuz.app.dev.ui

import android.content.BroadcastReceiver
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.view.GravityCompat
import androidx.fragment.app.viewModels
import androidx.lifecycle.LiveData
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.firebase.analytics.FirebaseAnalytics
import com.mobiuz.app.R
import com.mobiuz.app.databinding.ActivityMainBinding
import com.mobiuz.app.dev.MainViewModel
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.base.BaseFragment
import com.mobiuz.app.dev.ui.global.ButtonClick
import com.mobiuz.app.dev.ui.global.CONSTANTS
import com.mobiuz.app.dev.ui.settings.SettingsActivity
import com.mobiuz.app.dev.utils.extensions.customLog
import com.mobiuz.app.dev.utils.extensions.customMasketHome
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 MainFragment : BaseFragment(R.layout.fragment_main) {

    @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 onViewCreated(view: View, savedInstanceState: Bundle?) {
        _bn = ActivityMainBinding.bind(view)

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

        setUpUI()
        collects()
    }

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

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

        setUpUI()
        collects()


    }


    override 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 {
                        pref.clearUserData()
                        val intent = Intent(requireContext(), AuthActivity::class.java)
                        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
                        startActivity(intent)
                        requireActivity().finish()
                    }
                }
            })

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

            btnSupport.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navigateToSettingsScreen(CONSTANTS.SUPPORT)
                }
            })

            btnSafety.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navigateToSettingsScreen(CONSTANTS.SAFETY)
                }
            })

            header.headerLayout.setOnClickListener(object : ButtonClick() {
                override fun onSingleClick(v: View?) {
                    navigateToSettingsScreen(CONSTANTS.PROFILE)
                }
            })
            txtRedactData.setOnClickListener {
            }

            txtPublicOferta.setOnClickListener {
            }
            txtConfidensialnost.setOnClickListener {
            }
        }
    }

    private fun navigateToSettingsScreen(key: String) {
        val intent = Intent(requireContext(), SettingsActivity::class.java)
        intent.putExtra(CONSTANTS.TYPE_SETTINGS, key)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
        startActivity(intent)
    }

    override 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 -> {
                        pref.userName = it.data
                        bn.header.txtUserName.text = it.data
                        bn.header.txtAvatar.text = it.data[0].toString()
                    }
                    else -> Unit
                }
            }
        }

    }

    private fun setupBottomNavigationBar() {
        try {
            bottomNavigationView = requireActivity().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 = parentFragmentManager,
                containerId = R.id.nav_host_fragment,
                intent = requireActivity().intent
            )
            currentNavController = controller
        } catch (e: Exception) {
            e.printStackTrace()
        }

        requireActivity()
    }


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

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