package com.example.pap_findu;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.pap_findu.models.User;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class CriarConta extends AppCompatActivity {

    private EditText inputFullName, emailEditText, passwordEditText, inputConfirmPassword;
    private CheckBox checkTerms;
    private Button btnCreateAccount;
    private TextView loginLink;
    private FirebaseAuth mAuth;
    private DatabaseReference mDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_criar_conta);

        // Ajuste de Padding para EdgeToEdge
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 1. Inicializar Firebase
        mAuth = FirebaseAuth.getInstance();
        mDatabase = FirebaseDatabase.getInstance().getReference("users");

        // 2. Inicializar Views
        inputFullName = findViewById(R.id.inputFullName);
        emailEditText = findViewById(R.id.emailEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        inputConfirmPassword = findViewById(R.id.inputConfirmPassword);
        checkTerms = findViewById(R.id.checkTerms);
        btnCreateAccount = findViewById(R.id.btnCreateAccount);
        loginLink = findViewById(R.id.loginLink);

        // 3. Botão Criar Conta
        btnCreateAccount.setOnClickListener(v -> validarECriar());

        // 4. Link para Login
        loginLink.setOnClickListener(v -> {
            startActivity(new Intent(CriarConta.this, login_activity.class));
            finish();
        });
    }

    private void validarECriar() {
        String fullName = inputFullName.getText().toString().trim();
        String email = emailEditText.getText().toString().trim();
        String password = passwordEditText.getText().toString().trim();
        String confirmPassword = inputConfirmPassword.getText().toString().trim();

        // Validações Básicas
        if (fullName.isEmpty() || email.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(this, "Preencha todos os campos!", Toast.LENGTH_SHORT).show();
            return;
        }

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

        if (!checkTerms.isChecked()) {
            Toast.makeText(this, "Aceite os termos de serviço!", Toast.LENGTH_SHORT).show();
            return;
        }

        // Criar no FirebaseAuth
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        salvarDadosNoPerfil(fullName, email);
                    } else {
                        Toast.makeText(CriarConta.this, "Erro: " + task.getException().getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
    }

    private void salvarDadosNoPerfil(String fullName, String email) {
        FirebaseUser firebaseUser = mAuth.getCurrentUser();
        if (firebaseUser != null) {
            String userId = firebaseUser.getUid();

            // Usamos o teu modelo User (Mapping: fullName -> name)
            User user = new User(fullName, email);

            mDatabase.child(userId).setValue(user)
                    .addOnCompleteListener(task -> {
                        if (task.isSuccessful()) {
                            Toast.makeText(CriarConta.this, "Conta configurada com sucesso!", Toast.LENGTH_SHORT).show();
                            // Só avança se os dados foram salvos
                            Intent intent = new Intent(CriarConta.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        } else {
                            Toast.makeText(CriarConta.this, "Erro ao salvar perfil no banco de dados.", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }
}