package com.example.vdcscore;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
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 RecuperarPasswordActivity extends AppCompatActivity {

    private TextInputEditText editEmailRecuperar;
    private Button btnRecuperar;
    private ImageButton btnBack;
    private TextView txtVoltarLogin;
    private FirebaseAuth mAuth;

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

        editEmailRecuperar = findViewById(R.id.editEmailRecuperar);
        btnRecuperar = findViewById(R.id.btnRecuperar);
        btnBack = findViewById(R.id.btnBack);
        txtVoltarLogin = findViewById(R.id.txtVoltarLogin);

        mAuth = FirebaseAuth.getInstance();

        btnRecuperar.setOnClickListener(v -> recuperarPassword());
        btnBack.setOnClickListener(v -> voltarLogin());
        txtVoltarLogin.setOnClickListener(v -> voltarLogin());
    }

    private void recuperarPassword() {
        String email = editEmailRecuperar.getText().toString().trim();

        if (email.isEmpty()) {
            Toast.makeText(this, "Por favor, introduza o seu email", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            Toast.makeText(this, "Por favor, introduza um email válido", Toast.LENGTH_SHORT).show();
            return;
        }

        mAuth.sendPasswordResetEmail(email)
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        Toast.makeText(this, 
                                "Email de recuperação enviado! Verifique a sua caixa de entrada.",
                                Toast.LENGTH_LONG).show();
                        voltarLogin();
                    } else {
                        String errorMessage = com.example.vdcscore.utils.FirebaseErrorUtils.getErrorMessagePt(task.getException());
                        Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
                    }
                });
    }

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

