package com.example.cuida.ui.auth;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.cuida.data.model.User;
import com.example.cuida.databinding.ActivityRegisterBinding;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;

public class RegisterActivity extends AppCompatActivity {

    private ActivityRegisterBinding binding;
    private FirebaseAuth mAuth;

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

        binding.registerButton.setOnClickListener(v -> register());
        binding.loginLink.setOnClickListener(v -> {
            startActivity(new Intent(this, LoginActivity.class));
            finish();
        });

        String[] genders = new String[]{"Masculino", "Feminino"};
        android.widget.ArrayAdapter<String> adapter = new android.widget.ArrayAdapter<>(
                this, android.R.layout.simple_dropdown_item_1line, genders);
        binding.genderAutoComplete.setAdapter(adapter);
    }

    private void register() {
        String name = binding.nameEditText.getText().toString();
        String ageStr = binding.ageEditText.getText().toString();
        String utenteStr = binding.utenteEditText.getText().toString();
        String email = binding.emailEditText.getText().toString();
        String password = binding.passwordEditText.getText().toString();
        String gender = binding.genderAutoComplete.getText().toString();

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

        if (utenteStr.length() != 9) {
            Toast.makeText(this, "Utente deve ter 9 dígitos.", Toast.LENGTH_SHORT).show();
            return;
        }

        int age = Integer.parseInt(ageStr);

        binding.registerButton.setEnabled(false);
        binding.registerButton.setText("A registar...");

        mAuth = FirebaseAuth.getInstance();
        FirebaseFirestore db = FirebaseFirestore
                .getInstance();
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        // Registration success, save additional info to Firestore
                        FirebaseUser firebaseUser = mAuth.getCurrentUser();
                        if (firebaseUser != null) {
                            saveUserData(firebaseUser.getUid(), name, email, ageStr, utenteStr, gender);
                        }
                    } else {
                        Exception e = task.getException();
                        if (e instanceof com.google.firebase.auth.FirebaseAuthUserCollisionException) {
                            // Tenta fazer login automático para reparar o perfil se ele não existir no Firestore
                            mAuth.signInWithEmailAndPassword(email, password)
                                    .addOnSuccessListener(authResult -> {
                                        saveUserData(authResult.getUser().getUid(), name, email, ageStr, utenteStr, gender);
                                    })
                                    .addOnFailureListener(err -> {
                                        binding.registerButton.setEnabled(true);
                                        binding.registerButton.setText("Registar");
                                        Toast.makeText(RegisterActivity.this, "Email já registado.", Toast.LENGTH_SHORT).show();
                                    });
                        } else {
                            binding.registerButton.setEnabled(true);
                            binding.registerButton.setText("Registar");
                            String errorMsg = e != null ? e.getMessage() : "Erro desconhecido";
                            Toast.makeText(RegisterActivity.this, "Erro: " + errorMsg, Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    private void saveUserData(String userId, String name, String email, String ageStr, String utenteStr, String gender) {
        FirebaseFirestore db = FirebaseFirestore.getInstance();
        java.util.Map<String, Object> userMap = new java.util.HashMap<>();
        userMap.put("id", userId);
        userMap.put("nome_completo", name);
        userMap.put("email", email);
        try {
            userMap.put("idade", Integer.parseInt(ageStr));
        } catch (NumberFormatException e) {
            userMap.put("idade", 0);
        }
        userMap.put("numero_utente", utenteStr);
        userMap.put("sexo", gender);
        userMap.put("tipo", "paciente");
        userMap.put("profilePictureUri", "");

        db.collection("utilizadores").document(userId)
                .set(userMap)
                .addOnSuccessListener(aVoid -> {
                    Toast.makeText(RegisterActivity.this, "Conta criada!", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                    finish();
                })
                .addOnFailureListener(e -> {
                    binding.registerButton.setEnabled(true);
                    binding.registerButton.setText("Registar");
                    Toast.makeText(RegisterActivity.this, "Erro ao guardar dados.", Toast.LENGTH_SHORT).show();
                });
    }
}