package com.example.cuida.ui.auth;

import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.cuida.databinding.ActivityForgotPasswordBinding;

public class ForgotPasswordActivity extends AppCompatActivity {

    private ActivityForgotPasswordBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityForgotPasswordBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.resetButton.setOnClickListener(v -> {
            String email = binding.emailEditText.getText().toString().trim();
            if (email.isEmpty()) {
                Toast.makeText(this, "Insira o seu email.", Toast.LENGTH_SHORT).show();
            } else {
                // Real Firebase Password Reset Logic
                com.google.firebase.auth.FirebaseAuth.getInstance().sendPasswordResetEmail(email)
                        .addOnCompleteListener(task -> {
                            if (task.isSuccessful()) {
                                Toast.makeText(this, "Email enviado!", Toast.LENGTH_SHORT).show();
                                finish();
                            } else {
                                String errorMsg = task.getException() != null ? task.getException().getMessage() : "Erro desconhecido";
                                if (errorMsg != null) {
                                    if (errorMsg.contains("There is no user record")) {
                                        errorMsg = "Não existe conta associada a este email.";
                                    } else if (errorMsg.contains("badly formatted")) {
                                        errorMsg = "O formato do email é inválido.";
                                    }
                                }
                                Toast.makeText(this, "Erro: " + errorMsg, Toast.LENGTH_LONG).show();
                            }
                        });
            }
        });

        binding.backToLogin.setOnClickListener(v -> finish());
    }
}
