package partisan.weforge.xyz.pulse

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import partisan.weforge.xyz.pulse.databinding.ActivityMainBinding
import androidx.appcompat.app.ActionBarDrawerToggle
import partisan.weforge.xyz.pulse.REQUIRED_PERMISSIONS
import partisan.weforge.xyz.pulse.hasCallRedirectionRole
import partisan.weforge.xyz.pulse.hasDrawOverlays
import partisan.weforge.xyz.pulse.hasGeneralPermissions
import com.google.android.material.switchmaterial.SwitchMaterial

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var prefs: Preferences

    private var popupSwitch: SwitchMaterial? = null
    private var popupMenuItem: MenuItem? = null

    val popupToggle: SwitchMaterial
        get() = findViewById(R.id.globalPopupToggle)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        prefs = Preferences(this) 
        updateDonationIcon()
        setContentView(binding.root)
        prefs = Preferences(this)
        setSupportActionBar(binding.topAppBar)

        val drawerToggle = ActionBarDrawerToggle(
            this,
            binding.drawerLayout,
            binding.topAppBar,
            R.string.navigation_drawer_open,
            R.string.navigation_drawer_open // The "close" string is never actually shown in the UI, so I reuse "navigation_drawer_open" as sort of a placeholder
        )
        binding.drawerLayout.addDrawerListener(drawerToggle)
        drawerToggle.syncState()

        supportFragmentManager.beginTransaction()
            .replace(R.id.fragmentContainer, MainFragment())
            .commit()

        setupPopupToggle(false)

        binding.navigationView.setNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.action_home -> {
                    supportFragmentManager.popBackStack(null, androidx.fragment.app.FragmentManager.POP_BACK_STACK_INCLUSIVE)
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentContainer, MainFragment())
                        .commit()
                    true
                }
                R.id.action_popup_settings -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentContainer, PopupSettingsFragment())
                        .addToBackStack(null)
                        .commit()
                    true
                }
                R.id.action_about -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentContainer, AboutFragment())
                        .addToBackStack(null)
                        .commit()
                    true
                }
                R.id.action_services -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentContainer, ServiceSettingsFragment())
                        .addToBackStack(null)
                        .commit()
                    true
                }
                R.id.action_redirect_settings -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentContainer, RedirectSettingsFragment())
                        .addToBackStack(null)
                        .commit()
                    true
                }
                R.id.action_contacts -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentContainer, ContactsFragment())
                        .addToBackStack(null)
                        .commit()
                    true
                }
                R.id.action_donate -> {
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.fragmentContainer, DonateFragment())
                        .addToBackStack(null)
                        .commit()
                    true
                }
                else -> false
            }.also {
                binding.drawerLayout.closeDrawers()
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.topbar_toggle, menu)
        popupMenuItem = menu.findItem(R.id.globalPopupToggle)
        popupSwitch = popupMenuItem?.actionView?.findViewById(R.id.globalPopupToggle)
        popupMenuItem?.isVisible = false // hide by default
        return true
    }

    fun setupPopupToggle(
        visible: Boolean,
        initialState: Boolean = false,
        onToggle: ((Boolean) -> Unit)? = null
    ) {
        popupMenuItem?.isVisible = visible
        popupSwitch?.apply {
            setOnCheckedChangeListener(null)
            isChecked = initialState
            setOnCheckedChangeListener { _, isChecked ->
                onToggle?.invoke(isChecked)
            }
        }
    }

    private fun updateDonationIcon() {
        val donateItem = binding.navigationView.menu.findItem(R.id.action_donate)
        donateItem.setIcon(
            if (prefs.isDonationActivated)
                R.drawable.heart_filled_24
            else
                R.drawable.heart_24
        )
    }

    fun setAppBarTitle(vararg parts: String) {
        binding.topAppBar.title = parts.joinToString(" > ")
    }

    private fun hasPermissions(): Boolean {
        return hasGeneralPermissions(this) &&
               hasDrawOverlays(this) &&
               hasCallRedirectionRole(this)
    }
}
