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.AppDatabase;
import com.example.cuida.data.dao.UserDao;
import com.example.cuida.data.model.User;
import com.example.cuida.databinding.ActivityRegisterBinding;

public class RegisterActivity extends AppCompatActivity {

    private ActivityRegisterBinding binding;

    @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();
        });
    }

    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();

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

        int age = Integer.parseInt(ageStr);

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

        com.google.firebase.auth.FirebaseAuth mAuth = com.google.firebase.auth.FirebaseAuth.getInstance();
        com.google.firebase.firestore.FirebaseFirestore db = com.google.firebase.firestore.FirebaseFirestore
                .getInstance();

        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        // Registration success, save additional info to Firestore
                        com.google.firebase.auth.FirebaseUser firebaseUser = mAuth.getCurrentUser();
                        if (firebaseUser != null) {
                            String userId = firebaseUser.getUid();

                            java.util.Map<String, Object> userMap = new java.util.HashMap<>();
                            userMap.put("uid", userId);
                            userMap.put("name", name);
                            userMap.put("email", email);
                            userMap.put("age", age);
                            userMap.put("utenteNumber", utenteStr);
                            userMap.put("profilePictureUri", ""); // Init empty

                            db.collection("users").document(userId)
                                    .set(userMap)
                                    .addOnSuccessListener(aVoid -> {
                                        // Optional: Also save to local Room DB for offline cache if desired,
                                        // but for now we focus on Firebase as requested.

                                        Toast.makeText(RegisterActivity.this, "Conta criada com sucesso!",
                                                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 salvar dados: " + e.getMessage(),
                                                Toast.LENGTH_SHORT).show();
                                    });
                        }
                    } else {
                        binding.registerButton.setEnabled(true);
                        binding.registerButton.setText("Registar");
                        Toast.makeText(RegisterActivity.this, "Falha no registo: " + task.getException().getMessage(),
                                Toast.LENGTH_SHORT).show();
                    }
                });
    }
}
