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

        AppDatabase db = AppDatabase.getDatabase(getApplicationContext());
        UserDao userDao = db.userDao();

        AppDatabase.databaseWriteExecutor.execute(() -> {
            User existing = userDao.checkUser(email);
            if (existing != null) {
                runOnUiThread(() -> Toast.makeText(this, "Email já registado", Toast.LENGTH_SHORT).show());
            } else {
                User newUser = new User(name, email, password, age, utenteStr);
                userDao.insert(newUser);
                runOnUiThread(() -> {
                    Toast.makeText(this, "Conta criada com sucesso!", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(this, LoginActivity.class));
                    finish();
                });
            }
        });
    }
}
