package com.example.cuida.ui.auth;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.cuida.databinding.ActivityResetPasswordBinding;
import com.google.firebase.auth.FirebaseAuth;

public class ResetPasswordActivity extends AppCompatActivity {

    private ActivityResetPasswordBinding binding;
    private String oobCode;

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

        // Use custom uri scheme or https scheme, extracting oobCode parameter
        Intent intent = getIntent();
        if (intent != null && intent.getData() != null) {
            Uri data = intent.getData();
            oobCode = data.getQueryParameter("oobCode");

            if (oobCode == null || oobCode.isEmpty()) {
                Toast.makeText(this, "Link inválido.", Toast.LENGTH_SHORT).show();
                finish();
            }
        } else {
            Toast.makeText(this, "Código não encontrado.", Toast.LENGTH_SHORT).show();
            finish();
        }

        binding.saveNewPasswordButton.setOnClickListener(v -> saveNewPassword());
    }

    private void saveNewPassword() {
        String newPassword = binding.newPasswordEditText.getText().toString();
        String confirmPassword = binding.confirmNewPasswordEditText.getText().toString();

        if (newPassword.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(this, "Preencha as passwords.", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!newPassword.equals(confirmPassword)) {
            Toast.makeText(this, "Pass não coincidem.", Toast.LENGTH_SHORT).show();
            return;
        }

        if (newPassword.length() < 6) {
            Toast.makeText(this, "Mínimo 6 caracteres.", Toast.LENGTH_SHORT).show();
            return;
        }

        binding.saveNewPasswordButton.setEnabled(false);
        binding.saveNewPasswordButton.setText("A guardar...");

        FirebaseAuth.getInstance().confirmPasswordReset(oobCode, newPassword)
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful()) {
                        Toast.makeText(this, "Pass atualizada!", Toast.LENGTH_SHORT).show();
                        // Go back to login screen
                        Intent intent = new Intent(ResetPasswordActivity.this, LoginActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        finish();
                    } else {
                        binding.saveNewPasswordButton.setEnabled(true);
                        binding.saveNewPasswordButton.setText("Guardar Palavra-passe");
                        
                        String errorMsg = task.getException() != null ? task.getException().getMessage() : "Erro desconhecido";
                        Toast.makeText(this, "Erro: " + errorMsg, Toast.LENGTH_LONG).show();
                    }
                });
    }
}
