package com.example.pap_findu;

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

import com.example.pap_findu.models.User;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

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

public class CriarConta extends AppCompatActivity {

    private EditText inputFullName;
    private EditText emailEditText;
    private EditText passwordEditText;
    private EditText inputConfirmPassword;
    private CheckBox checkTerms;
    private Button btnCreateAccount;
    private TextView loginLink;
    private com.google.firebase.auth.FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_criar_conta);
        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;
        });

        // Initialize 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);

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

        // Set click listener for the create account button
        btnCreateAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String fullName = inputFullName.getText().toString();
                String email = emailEditText.getText().toString();
                String password = passwordEditText.getText().toString();
                String confirmPassword = inputConfirmPassword.getText().toString();

                if (fullName.isEmpty() || email.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()) {
                    Toast.makeText(CriarConta.this, "Por favor, preencha todos os campos.", Toast.LENGTH_SHORT).show();
                } else if (!password.equals(confirmPassword)) {
                    Toast.makeText(CriarConta.this, "As palavras-passe não coincidem.", Toast.LENGTH_SHORT).show();
                } else if (!checkTerms.isChecked()) {
                    Toast.makeText(CriarConta.this, "Você deve concordar com os Termos de Serviço.", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    mAuth.createUserWithEmailAndPassword(email, password)
                            .addOnCompleteListener(CriarConta.this,
                                    new com.google.android.gms.tasks.OnCompleteListener<com.google.firebase.auth.AuthResult>() {
                                        @Override
                                        public void onComplete(
                                                @androidx.annotation.NonNull com.google.android.gms.tasks.Task<com.google.firebase.auth.AuthResult> task) {
                                            if (task.isSuccessful()) {
                                                // Sign in success, update UI with the signed-in user's information
                                                Toast.makeText(CriarConta.this, "Conta criada com sucesso!",
                                                        Toast.LENGTH_SHORT).show();
                                                com.google.firebase.auth.FirebaseUser firebaseUser = mAuth
                                                        .getCurrentUser();

                                                // Save user data to Realtime Database
                                                if (firebaseUser != null) {
                                                    String userId = firebaseUser.getUid();
                                                    DatabaseReference mDatabase = FirebaseDatabase.getInstance()
                                                            .getReference("users");
                                                    User user = new User(fullName, email);

                                                    mDatabase.child(userId).setValue(user)
                                                            .addOnCompleteListener(task1 -> {
                                                                if (!task1.isSuccessful()) {
                                                                    Toast.makeText(CriarConta.this,
                                                                            "Falha ao salvar dados do perfil.",
                                                                            Toast.LENGTH_SHORT).show();
                                                                }
                                                            });
                                                }
                                                Intent intent = new Intent(CriarConta.this, MainActivity.class);
                                                startActivity(intent);
                                                finish();
                                            } else {
                                                // If sign in fails, display a message to the user.
                                                Toast.makeText(CriarConta.this,
                                                        "Falha ao criar conta: " + task.getException().getMessage(),
                                                        Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                }
            }
        });

        // Set click listener for the login link text
        loginLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Navigate back to the login activity
                Intent intent = new Intent(CriarConta.this, login_activity.class);
                startActivity(intent);
                finish();
            }
        });
    }
}
