package com.example.finzora;

import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    // Declaração das variáveis
    private EditText inputEmail, inputPassword;
    private Button btnLogin;
    private TextView btnRegister;

    // Credenciais para teste
    private final String TEST_EMAIL = "teste@email.com";
    private final String TEST_PASSWORD = "123456";

    // Para controlar o double back press
    private boolean doubleBackToExitPressedOnce = false;

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

        // Configurar o botão voltar (nova forma)
        setupBackButton();

        // Inicializar views
        initializeViews();

        // Configurar botão de Login
        setupLoginButton();

        // Configurar link de Registro
        setupRegisterButton();
    }

    private void setupBackButton() {
        // Nova forma de tratar o botão voltar (Android 13+)
        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                // Para sair do app com double back press
                if (doubleBackToExitPressedOnce) {
                    // Se já pressionou uma vez, sai do app
                    finish();
                } else {
                    // Primeira vez que pressiona
                    doubleBackToExitPressedOnce = true;
                    Toast.makeText(MainActivity.this,
                            "Pressione VOLTAR novamente para sair",
                            Toast.LENGTH_SHORT).show();

                    // Reset após 2 segundos
                    getWindow().getDecorView().postDelayed(() ->
                            doubleBackToExitPressedOnce = false, 2000);
                }
            }
        });
    }

    private void initializeViews() {
        inputEmail = findViewById(R.id.inputEmail);
        inputPassword = findViewById(R.id.inputPassword);
        btnLogin = findViewById(R.id.btnLogin);
        btnRegister = findViewById(R.id.btnRegister);
    }

    private void setupLoginButton() {
        btnLogin.setOnClickListener(v -> realizarLogin());
    }

    private void setupRegisterButton() {
        btnRegister.setOnClickListener(v -> abrirTelaRegistro());
    }

    private void realizarLogin() {
        // Obter valores dos campos
        String email = inputEmail.getText().toString().trim();
        String password = inputPassword.getText().toString().trim();

        // Validar campos vazios
        if (email.isEmpty()) {
            inputEmail.setError("Digite seu email");
            inputEmail.requestFocus();
            return;
        }

        if (password.isEmpty()) {
            inputPassword.setError("Digite sua senha");
            inputPassword.requestFocus();
            return;
        }

        // Validar formato do email
        if (!isValidEmail(email)) {
            inputEmail.setError("Digite um email válido");
            inputEmail.requestFocus();
            return;
        }

        // Verificar credenciais
        if (email.equals(TEST_EMAIL) && password.equals(TEST_PASSWORD)) {
            // Login bem-sucedido
            Toast.makeText(this, "Login realizado com sucesso!", Toast.LENGTH_SHORT).show();

            // Ir para HomeActivity
            Intent intent = new Intent(MainActivity.this, HomeActivity.class);
            startActivity(intent);

            // Fechar esta activity
            finish();
        } else {
            // Credenciais incorretas
            Toast.makeText(this, "Email ou senha incorretos", Toast.LENGTH_SHORT).show();
            inputPassword.setText("");
            inputPassword.requestFocus();
        }
    }

    private boolean isValidEmail(String email) {
        return email.contains("@") && email.contains(".");
    }

    private void abrirTelaRegistro() {
        try {
            Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
            startActivityForResult(intent, 100);
        } catch (Exception e) {
            Toast.makeText(this, "Erro ao abrir registro", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
            String novoEmail = data.getStringExtra("EMAIL");
            String novoPassword = data.getStringExtra("PASSWORD");

            if (novoEmail != null && novoPassword != null) {
                inputEmail.setText(novoEmail);
                inputPassword.setText(novoPassword);
                Toast.makeText(this, "Conta criada! Faça login.", Toast.LENGTH_SHORT).show();
            }
        }
    }

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

        // Limpar campo da senha quando voltar
        if (inputPassword != null) {
            inputPassword.setText("");
        }

        // Dar foco ao campo de email
        if (inputEmail != null) {
            inputEmail.requestFocus();
        }

        // Resetar o double back press
        doubleBackToExitPressedOnce = false;
    }
}