package com.fluxup.app;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.Locale;

public class SettingsActivity extends AppCompatActivity {

    private ImageButton btnBack;
    private SwitchMaterial switchDarkMode, switchPrivacy, switchNotifications;
    private TextView tvEmail, btnChangePassword;
    private Spinner spinnerLanguage;
    private View btnLogout;
    private SharedPreferences sharedPreferences;
    private static final String PREFS_NAME = "FluxupSettings";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        sharedPreferences = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        
        // Aplicar o idioma guardado antes de carregar o layout
        String lang = sharedPreferences.getString("language", "pt");
        updateLocaleSilent(lang);
        
        // Aplicar tema guardado
        applyTheme(sharedPreferences.getBoolean("darkMode", false));
        
        setContentView(R.layout.activity_settings);

        initViews();
        setupListeners();
        loadSettings();
    }

    private void applyTheme(boolean isDarkMode) {
        if (isDarkMode) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        }
    }

    private void initViews() {
        btnBack = findViewById(R.id.btnBack);
        switchDarkMode = findViewById(R.id.switchDarkMode);
        switchPrivacy = findViewById(R.id.switchPrivacy);
        switchNotifications = findViewById(R.id.switchNotifications);
        tvEmail = findViewById(R.id.tvEmail);
        btnChangePassword = findViewById(R.id.btnChangePassword);
        spinnerLanguage = findViewById(R.id.spinnerLanguage);
        btnLogout = findViewById(R.id.btnLogout);

        // Configurar Spinner de Idiomas
        String[] languages = {"Português", "English", "Español"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, languages);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerLanguage.setAdapter(adapter);

        // Mostrar email do utilizador
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {
            tvEmail.setText(user.getEmail());
        }
    }

    private void setupListeners() {
        btnBack.setOnClickListener(v -> finish());

        switchDarkMode.setOnCheckedChangeListener((buttonView, isChecked) -> {
            applyTheme(isChecked);
            saveSetting("darkMode", isChecked);
        });

        switchPrivacy.setOnCheckedChangeListener((buttonView, isChecked) -> saveSetting("privacy", isChecked));
        switchNotifications.setOnCheckedChangeListener((buttonView, isChecked) -> saveSetting("notifications", isChecked));

        btnLogout.setOnClickListener(v -> {
            FirebaseAuth.getInstance().signOut();
            Intent intent = new Intent(SettingsActivity.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();
        });

        spinnerLanguage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedLang = "pt";
                if (position == 1) selectedLang = "en";
                else if (position == 2) selectedLang = "es";
                
                String currentLang = sharedPreferences.getString("language", "pt");
                if (!selectedLang.equals(currentLang)) {
                    saveSetting("language", selectedLang);
                    updateLocale(selectedLang);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        btnChangePassword.setOnClickListener(v -> {
            FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
            if (user != null && user.getEmail() != null) {
                FirebaseAuth.getInstance().sendPasswordResetEmail(user.getEmail())
                    .addOnCompleteListener(task -> {
                        if (task.isSuccessful()) {
                            Toast.makeText(this, "Email de redefinição enviado!", Toast.LENGTH_SHORT).show();
                        }
                    });
            }
        });
    }

    private void loadSettings() {
        switchDarkMode.setChecked(sharedPreferences.getBoolean("darkMode", false));
        switchPrivacy.setChecked(sharedPreferences.getBoolean("privacy", false));
        switchNotifications.setChecked(sharedPreferences.getBoolean("notifications", true));
        
        String lang = sharedPreferences.getString("language", "pt");
        if (lang.equals("en")) spinnerLanguage.setSelection(1, false);
        else if (lang.equals("es")) spinnerLanguage.setSelection(2, false);
        else spinnerLanguage.setSelection(0, false);
    }

    private void updateLocaleSilent(String langCode) {
        Locale locale = new Locale(langCode);
        Locale.setDefault(locale);
        Resources resources = getResources();
        Configuration config = resources.getConfiguration();
        config.setLocale(locale);
        resources.updateConfiguration(config, resources.getDisplayMetrics());
    }

    private void updateLocale(String langCode) {
        updateLocaleSilent(langCode);
        Intent intent = new Intent(this, SettingsActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }

    private void saveSetting(String key, boolean value) {
        sharedPreferences.edit().putBoolean(key, value).apply();
    }

    private void saveSetting(String key, String value) {
        sharedPreferences.edit().putString(key, value).apply();
    }
}
