package com.gestoreasy.ui

import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.gestoreasy.MobileApp
import com.gestoreasy.R
import com.gestoreasy.databinding.ActivityMainBinding
import com.gestoreasy.services.PushNotificationService
import com.gestoreasy.ui.animations.AnimationUtils
import com.google.android.material.navigation.NavigationView
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
    private lateinit var binding: ActivityMainBinding
    private lateinit var app: MobileApp
    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var pushNotificationService: PushNotificationService
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        app = MobileApp.get(this)
        pushNotificationService = PushNotificationService(this)
        
        setSupportActionBar(binding.appBarMain.toolbar)
        
        val drawerLayout: DrawerLayout = binding.drawerLayout
        val navView: NavigationView = binding.navView
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        
        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.nav_dashboard,
                R.id.nav_products,
                R.id.nav_clients,
                R.id.nav_orders,
                R.id.nav_goals,
                R.id.nav_reports,
                R.id.nav_routes
            ),
            drawerLayout
        )
        
        setupActionBarWithNavController(navController, appBarConfiguration)
        navView.setupWithNavController(navController)
        navView.setNavigationItemSelectedListener(this)
        
        // Animar entrada
        AnimationUtils.fadeIn(binding.root, 400)
        
        // Sincronização automática ao abrir
        lifecycleScope.launch {
            try {
                app.syncManager.syncAll(force = false)
                pushNotificationService.showSyncNotification(
                    success = true,
                    itemsSynced = 0
                )
            } catch (e: Exception) {
                pushNotificationService.showSyncNotification(success = false)
            }
        }
    }
    
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        return true
    }
    
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_sync -> {
                syncData()
                true
            }
            R.id.action_settings -> {
                // TODO: Abrir configurações
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
    
    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }
    
    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.nav_dashboard -> {
                // Já está na dashboard
            }
            R.id.nav_products -> {
                // TODO: Navegar para produtos
            }
            R.id.nav_clients -> {
                startActivity(Intent(this, com.gestoreasy.ui.client.ClientFormActivity::class.java))
            }
            R.id.nav_orders -> {
                // TODO: Navegar para pedidos
            }
            R.id.nav_goals -> {
                startActivity(Intent(this, com.gestoreasy.ui.goals.GoalsActivity::class.java))
            }
            R.id.nav_reports -> {
                startActivity(Intent(this, com.gestoreasy.ui.reports.ReportsActivity::class.java))
            }
            R.id.nav_routes -> {
                startActivity(Intent(this, com.gestoreasy.ui.routes.RoutesActivity::class.java))
            }
            R.id.nav_logout -> {
                logout()
            }
        }
        
        binding.drawerLayout.closeDrawer(GravityCompat.START)
        return true
    }
    
    private fun syncData() {
        lifecycleScope.launch {
            try {
                Toast.makeText(this@MainActivity, "Sincronizando...", Toast.LENGTH_SHORT).show()
                app.syncManager.syncAll(force = true)
                pushNotificationService.showSyncNotification(success = true, itemsSynced = 0)
                Toast.makeText(this@MainActivity, "Sincronização concluída!", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                pushNotificationService.showSyncNotification(success = false)
                Toast.makeText(this@MainActivity, "Erro na sincronização: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun logout() {
        val prefs = getSharedPreferences("gestoreasy_prefs", MODE_PRIVATE)
        prefs.edit().clear().apply()
        
        startActivity(Intent(this, com.gestoreasy.ui.auth.LoginActivity::class.java))
        finish()
    }
}
