package com.example.vdcscore;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.auth.FirebaseAuth;

public class LoginActivity extends AppCompatActivity {

    TextInputEditText editEmail, editPassword;
    Button btnLogin;
    CheckBox checkRememberMe;
    FirebaseAuth mAuth;

    private TextView criarContaTextView;
    private TextView txtForgotPassword;
    
    private static final String PREFS_NAME = "LoginPrefs";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_REMEMBER = "remember";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        editEmail = findViewById(R.id.editEmail);
        editPassword = findViewById(R.id.editPassword2);
        btnLogin = findViewById(R.id.btnLogin);
        checkRememberMe = findViewById(R.id.checkRememberMe);
        criarContaTextView = findViewById(R.id.txtRegister);
        txtForgotPassword = findViewById(R.id.txtForgotPassword);

        mAuth = FirebaseAuth.getInstance();

        btnLogin.setOnClickListener(v -> loginUser());
        criarContaTextView.setOnClickListener(view -> criarConta());
        txtForgotPassword.setOnClickListener(view -> recuperarPassword());
        
        // Carregar credenciais guardadas
        loadSavedCredentials();
    }

    private void loadSavedCredentials() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        boolean remember = prefs.getBoolean(KEY_REMEMBER, false);
        
        if (remember) {
            String savedEmail = prefs.getString(KEY_EMAIL, "");
            String savedPassword = prefs.getString(KEY_PASSWORD, "");
            
            if (!savedEmail.isEmpty() && !savedPassword.isEmpty()) {
                editEmail.setText(savedEmail);
                editPassword.setText(savedPassword);
                checkRememberMe.setChecked(true);
                
                // Tentar login automático
                autoLogin(savedEmail, savedPassword);
            }
        }
    }

    private void autoLogin(String email, String password) {
        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        // Login automático bem-sucedido
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);
                        finish();
                    } else {
                        // Se o login automático falhar, apenas limpar a password do campo
                        // O utilizador pode tentar fazer login manualmente
                        editPassword.setText("");
                    }
                });
    }

    private void criarConta() {
        Intent intent= new Intent(LoginActivity.this, CriarContaActivity.class);
        startActivity(intent);
    }

    private void recuperarPassword() {
        Intent intent = new Intent(LoginActivity.this, RecuperarPasswordActivity.class);
        startActivity(intent);
    }

    private void loginUser() {
        String email = editEmail.getText().toString().trim();
        String password = editPassword.getText().toString().trim();

        if (email.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "Preencha todos os campos", Toast.LENGTH_SHORT).show();
            return;
        }

        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        // Guardar credenciais se "Lembrar-me" estiver marcado
                        if (checkRememberMe.isChecked()) {
                            saveCredentials(email, password);
                        } else {
                            clearSavedCredentials();
                        }

                        Toast.makeText(this, "Login efetuado!", Toast.LENGTH_SHORT).show();

                        // Abre a tua página principal
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        startActivity(intent);
                        finish();

                    } else {
                        String errorMessage = com.example.vdcscore.utils.FirebaseErrorUtils.getErrorMessagePt(task.getException());
                        Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
                    }
                });
    }
    
    private void saveCredentials(String email, String password) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(KEY_EMAIL, email);
        editor.putString(KEY_PASSWORD, password);
        editor.putBoolean(KEY_REMEMBER, true);
        editor.apply();
    }
    
    private void clearSavedCredentials() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.clear();
        editor.apply();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Verificar se já está autenticado (caso o login automático não tenha funcionado)
        if (FirebaseAuth.getInstance().getCurrentUser() != null){
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            finish();
        }
    }
}
