package com.example.elva

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import androidx.appcompat.app.AppCompatActivity
import com.example.elva.databinding.ActivityMainBinding
import com.example.elva.util.AuthManager
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding

    @Inject
    lateinit var authManager: AuthManager

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

        // Скрываем ActionBar по умолчанию (будет показан только для основных экранов)
        supportActionBar?.hide()

        val navController = (supportFragmentManager
            .findFragmentById(R.id.nav_host_fragment_content_main) as NavHostFragment)
            .navController

        // Определяем стартовый фрагмент
        val sharedPref = getSharedPreferences("elva_prefs", MODE_PRIVATE)
        val onboardingCompleted = sharedPref.getBoolean("onboarding_completed", false)
        val hasToken = authManager.getAccessToken() != null
        val isLoggedIn = authManager.isLoggedIn()

        android.util.Log.d("MainActivity", "onCreate: onboardingCompleted=$onboardingCompleted")
        android.util.Log.d("MainActivity", "onCreate: hasToken=$hasToken")
        android.util.Log.d("MainActivity", "onCreate: isLoggedIn=$isLoggedIn")

        // Настраиваем граф навигации с правильным стартовым фрагментом
        val navGraph = navController.navInflater.inflate(R.navigation.mobile_navigation)

        when {
            !onboardingCompleted -> {
                // Показываем onboarding
                android.util.Log.d("MainActivity", "Starting with onboarding")
                navGraph.setStartDestination(R.id.onboardingFragment)
            }
            isLoggedIn -> {
                // Пользователь авторизован и токен действителен - показываем dashboard
                android.util.Log.d("MainActivity", "User is logged in with valid token, starting with dashboard")
                navGraph.setStartDestination(R.id.dashboardFragment)
            }
            hasToken -> {
                // Есть токен, но он истек - показываем экран входа
                android.util.Log.d("MainActivity", "Token expired, starting with login")
                navGraph.setStartDestination(R.id.loginFragment)
            }
            else -> {
                // Нет токена - показываем экран входа
                android.util.Log.d("MainActivity", "No token, starting with login")
                navGraph.setStartDestination(R.id.loginFragment)
            }
        }

        navController.graph = navGraph

        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.onboardingFragment,
                R.id.loginFragment,
                R.id.dashboardFragment,
                R.id.nav_profile,
                R.id.nav_sos,
                R.id.nav_alerts,
                R.id.nav_contacts,
                R.id.nav_calendar,
                R.id.nav_nutrition,
                R.id.nav_settings,
                R.id.nav_location,
                R.id.nav_safety
            ),
            binding.drawerLayout
        )
        binding.navView.setupWithNavController(navController)

        // Скрываем навбар, ActionBar и блокируем drawer для onboarding и auth экранов
        navController.addOnDestinationChangedListener { _, destination, _ ->
            android.util.Log.d("MainActivity", "Navigated to: ${destination.label}")
            val bottomNav = findViewById<android.view.View>(R.id.bottom_navigation)
            when (destination.id) {
                R.id.onboardingFragment,
                R.id.loginFragment -> {
                    // Скрываем навбар и ActionBar для onboarding и auth экранов
                    bottomNav?.visibility = android.view.View.GONE
                    supportActionBar?.hide()
                    binding.drawerLayout.setDrawerLockMode(androidx.drawerlayout.widget.DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
                }
                else -> {
                    // Показываем навбар но оставляем ActionBar скрытым для всех экранов
                    bottomNav?.visibility = android.view.View.VISIBLE
                    supportActionBar?.hide()
                    binding.drawerLayout.setDrawerLockMode(androidx.drawerlayout.widget.DrawerLayout.LOCK_MODE_UNLOCKED)
                    // Настраиваем кастомный навбар
                    setupBottomNavigation(navController)
                }
            }
        }
    }

    private fun setupBottomNavigation(navController: androidx.navigation.NavController) {
        findViewById<android.view.View>(R.id.nav_cycle)?.setOnClickListener {
            navController.navigate(R.id.nav_cycle)
        }

        findViewById<android.view.View>(R.id.nav_health)?.setOnClickListener {
            navController.navigate(R.id.dashboardFragment)
        }

        findViewById<android.view.View>(R.id.nav_sos)?.setOnClickListener {
            navController.navigate(R.id.nav_sos)
        }

        findViewById<android.view.View>(R.id.nav_chat)?.setOnClickListener {
            // TODO: Navigate to Chat fragment
        }

        findViewById<android.view.View>(R.id.nav_profile)?.setOnClickListener {
            navController.navigate(R.id.nav_profile)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.nav_settings -> {
                val navController = findNavController(R.id.nav_host_fragment_content_main)
                navController.navigate(R.id.nav_settings)
            }
        }
        return super.onOptionsItemSelected(item)
    }
}