package com.borjabolufer.elevate;

import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.borjabolufer.elevate.databinding.ActivityMainBinding;
import com.borjabolufer.elevate.model.Ejercicio;
import com.borjabolufer.elevate.model.Usuario;
import com.borjabolufer.elevate.model.UsuarioDbHelper;
import com.borjabolufer.elevate.ui.fragments.DetalleEjercicioFragment;
import com.borjabolufer.elevate.ui.fragments.HomeFragment;
import com.borjabolufer.elevate.ui.fragments.DietFragment;
import com.borjabolufer.elevate.utils.JsonParser;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String PREFS_NAME = "ElevatePrefs";
    private static final String KEY_USER_EMAIL = "user_email";

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;
    private String currentUserEmail;
    private UsuarioDbHelper dbHelper;
    private JsonParser jsonParser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        requestWindowFeature(Window.FEATURE_NO_TITLE);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());


        inicializarComponentes();


        setSupportActionBar(binding.appBarMain.toolbar);


        configurarNavegacion();


        limpiarNavegacionSiEsNecesario();
    }

    private void inicializarComponentes() {
        dbHelper = new UsuarioDbHelper(this);
        jsonParser = new JsonParser(this);


        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        currentUserEmail = prefs.getString(KEY_USER_EMAIL, null);

        Log.d(TAG, "Usuario actual: " + currentUserEmail);
    }

    private void configurarNavegacion() {
        DrawerLayout drawer = binding.drawerLayout;
        NavigationView navigationView = binding.navView;


        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home,
                R.id.nav_diet,
                R.id.nav_profile
        )
                .setOpenableLayout(drawer)
                .build();

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);


        navController.addOnDestinationChangedListener((controller, destination, arguments) -> {
            updateToolbarTitle(destination.getId());


            Log.d(TAG, "Navegando a: " + destination.getLabel() + " (ID: " + destination.getId() + ")");
        });


        configurarNavigationHeader(navigationView);
    }

    private void configurarNavigationHeader(NavigationView navigationView) {
        UsuarioDbHelper usuarioDbHelper = new UsuarioDbHelper(getApplicationContext());
        View headerView = navigationView.getHeaderView(0);
        TextView headerTitle = headerView.findViewById(R.id.nav_header_title);
        TextView headerSubtitle = headerView.findViewById(R.id.nav_header_subtitle);

        SharedPreferences prefs = getSharedPreferences("ElevatePrefs", MODE_PRIVATE);
        String email = prefs.getString("user_email", "usuario@desconocido.com");
        String nombre = usuarioDbHelper.obtenerNombreUsuario(email);

        headerTitle.setText(nombre != null ? nombre : "Usuario");
        headerSubtitle.setText(email);
    }


    private void limpiarNavegacionSiEsNecesario() {
        try {

            FragmentManager fm = getSupportFragmentManager();


            if (fm.getBackStackEntryCount() > 3) {
                Log.d(TAG, "Back stack muy grande (" + fm.getBackStackEntryCount() + "), limpiando...");


                while (fm.getBackStackEntryCount() > 1) {
                    fm.popBackStackImmediate();
                }
            }


            NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
            if (navController.getCurrentDestination() != null) {
                int currentId = navController.getCurrentDestination().getId();


                if (currentId != R.id.nav_home && currentId != R.id.nav_diet && currentId != R.id.nav_profile) {
                    Log.d(TAG, "Destino inválido detectado, navegando a home");
                    navController.navigate(R.id.nav_home);
                }
            }

        } catch (Exception e) {
            Log.e(TAG, "Error limpiando navegación", e);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();


        verificarEstadoNavegacion();
    }

    private void verificarEstadoNavegacion() {
        try {
            FragmentManager fm = getSupportFragmentManager();


            Log.d(TAG, "Fragments en back stack: " + fm.getBackStackEntryCount());


            for (int i = 0; i < fm.getBackStackEntryCount(); i++) {
                FragmentManager.BackStackEntry entry = fm.getBackStackEntryAt(i);
                if (entry.getName() != null && entry.getName().contains("Loading")) {
                    Log.d(TAG, "Detectado LoadingFragment problemático, limpiando...");
                    fm.popBackStackImmediate(entry.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
                    break;
                }
            }


            limpiarFragmentsHuerfanos();

        } catch (Exception e) {
            Log.e(TAG, "Error verificando navegación", e);
        }
    }


    private void limpiarFragmentsHuerfanos() {
        try {
            FragmentManager fm = getSupportFragmentManager();


            for (Fragment fragment : fm.getFragments()) {
                if (fragment != null && fragment.getClass().getSimpleName().contains("Loading")) {
                    Log.d(TAG, "Removiendo fragment huérfano: " + fragment.getClass().getSimpleName());
                    fm.beginTransaction()
                            .remove(fragment)
                            .commitAllowingStateLoss();
                }
            }
        } catch (Exception e) {
            Log.w(TAG, "Error limpiando fragments huérfanos", e);
        }
    }

    private void mostrarMensajeSinPlan() {
        Snackbar.make(binding.getRoot(),
                        "Complete su perfil para generar su plan personalizado",
                        Snackbar.LENGTH_LONG)
                .setAction("Completar", v -> {
                    Intent intent = new Intent(this, PreguntasActivity.class);
                    startActivity(intent);
                })
                .show();
    }

    private void iniciarEntrenamiento() {
        try {

            HomeFragment homeFragment = getCurrentHomeFragment();
            if (homeFragment != null) {


                Log.d(TAG, "Iniciando entrenamiento desde HomeFragment");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error al iniciar entrenamiento", e);
        }
    }

    private void verRecetaCompleta() {
        try {

            DietFragment dietFragment = getCurrentDietFragment();
            if (dietFragment != null) {


                Log.d(TAG, "Mostrando receta completa desde DietFragment");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error al mostrar receta", e);
        }
    }

    private HomeFragment getCurrentHomeFragment() {
        try {
            NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
            if (navController.getCurrentDestination() != null &&
                    navController.getCurrentDestination().getId() == R.id.nav_home) {



                return null;
            }
        } catch (Exception e) {
            Log.e(TAG, "Error al obtener HomeFragment", e);
        }
        return null;
    }

    private DietFragment getCurrentDietFragment() {
        try {
            NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
            if (navController.getCurrentDestination() != null &&
                    navController.getCurrentDestination().getId() == R.id.nav_diet) {


                return null;
            }
        } catch (Exception e) {
            Log.e(TAG, "Error al obtener DietFragment", e);
        }
        return null;
    }

    private void updateToolbarTitle(int destinationId) {
        String title;

        if (destinationId == R.id.nav_home) {
            title = "Entrenamientos";
        } else if (destinationId == R.id.nav_diet) {
            title = "Plan Nutricional";
        } else if (destinationId == R.id.nav_profile) {
            title = "Mi Perfil";
        } else {
            title = "Elevate Fitness";
        }

        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(title);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();













        return super.onOptionsItemSelected(item);
    }

    private void abrirConfiguracion() {
        Snackbar.make(binding.getRoot(), "Abriendo configuración...", Snackbar.LENGTH_SHORT).show();

    }

    private void sincronizarDatos() {
        Snackbar.make(binding.getRoot(), "Sincronizando datos...", Snackbar.LENGTH_LONG)
                .setAction("Cancelar", v -> {
                    Log.d(TAG, "Sincronización cancelada");
                })
                .show();


        new Thread(() -> {
            try {

                Thread.sleep(2000);

                runOnUiThread(() -> {
                    Snackbar.make(binding.getRoot(), "Datos sincronizados correctamente",
                            Snackbar.LENGTH_SHORT).show();
                });
            } catch (InterruptedException e) {
                Log.e(TAG, "Error en sincronización", e);
            }
        }).start();
    }

    private void refrescarDatos() {
        Log.d(TAG, "Refrescando datos de ejercicios y dietas");

        try {

            String planJson = dbHelper.obtenerPlanJson(currentUserEmail);

            if (planJson != null && !planJson.trim().isEmpty()) {

                NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);


                if (navController.getCurrentDestination() != null) {
                    int currentId = navController.getCurrentDestination().getId();

                    if (currentId == R.id.nav_home || currentId == R.id.nav_diet) {
                        Snackbar.make(binding.getRoot(), "Datos actualizados", Snackbar.LENGTH_SHORT).show();
                    }
                }
            } else {
                mostrarMensajeSinPlan();
            }
        } catch (Exception e) {
            Log.e(TAG, "Error al refrescar datos", e);
            Snackbar.make(binding.getRoot(), "Error al actualizar datos", Snackbar.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }


    @Override
    public void onBackPressed() {
        try {

            if (binding.drawerLayout.isDrawerOpen(binding.navView)) {
                binding.drawerLayout.closeDrawer(binding.navView);
                return;
            }


            FragmentManager fm = getSupportFragmentManager();
            if (fm.getBackStackEntryCount() > 0) {

                super.onBackPressed();
            } else {

                NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
                if (navController.getCurrentDestination() != null &&
                        navController.getCurrentDestination().getId() != R.id.nav_home) {

                    navController.navigate(R.id.nav_home);
                } else {

                    super.onBackPressed();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error en onBackPressed", e);
            super.onBackPressed();
        }
    }


    public String getCurrentUserEmail() {
        return currentUserEmail;
    }


    public UsuarioDbHelper getDbHelper() {
        return dbHelper;
    }


    public void navegarA(int destinationId) {
        try {
            NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);


            if (getSupportFragmentManager().getBackStackEntryCount() > 2) {
                limpiarNavegacionSiEsNecesario();
            }

            navController.navigate(destinationId);
        } catch (Exception e) {
            Log.e(TAG, "Error navegando a destino: " + destinationId, e);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


        if (dbHelper != null) {
            dbHelper.close();
        }


        binding = null;

        Log.d(TAG, "MainActivity destruida correctamente");
    }


    public void resetNavigation() {
        try {
            Log.d(TAG, "Reseteando navegación de emergencia");


            FragmentManager fm = getSupportFragmentManager();
            fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);


            NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
            navController.navigate(R.id.nav_home);

        } catch (Exception e) {
            Log.e(TAG, "Error en reset de navegación", e);

            recreate();
        }
    }
}