package com.example.pap_teste;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.pap_teste.models.User;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.button.MaterialButtonToggleGroup;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private FirebaseAuth mAuth;
    private FirebaseFirestore db;
    private boolean isLoginMode = true;

    private TextInputLayout layoutName;
    private TextInputEditText inputName, inputEmail, inputPassword;
    private MaterialButton btnPrimaryAction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();
        db = FirebaseFirestore.getInstance();

        // Check if user is already logged in
        if (mAuth.getCurrentUser() != null) {
            android.app.ActivityOptions options = android.app.ActivityOptions.makeCustomAnimation(this, android.R.anim.fade_in, android.R.anim.fade_out);
            startActivity(new Intent(this, ClientDashboardActivity.class), options.toBundle());
            finish();
            return;
        }

        initViews();
    }

    private void initViews() {
        layoutName = findViewById(R.id.layoutName);
        inputName = findViewById(R.id.inputName);
        inputEmail = findViewById(R.id.inputEmail);
        inputPassword = findViewById(R.id.inputPassword);
        btnPrimaryAction = findViewById(R.id.btnPrimaryAction);
        MaterialButtonToggleGroup toggleGroup = findViewById(R.id.toggleGroup);

        toggleGroup.addOnButtonCheckedListener((group, checkedId, isChecked) -> {
            if (isChecked) {
                isLoginMode = checkedId == R.id.btnEntrar;
                layoutName.setVisibility(isLoginMode ? View.GONE : View.VISIBLE);
                btnPrimaryAction.setText(isLoginMode ? "Entrar" : "Criar Conta");
                findViewById(R.id.txtForgotPassword).setVisibility(isLoginMode ? View.VISIBLE : View.GONE);
            }
        });

        btnPrimaryAction.setOnClickListener(v -> handleAuth());
        
        findViewById(R.id.txtForgotPassword).setOnClickListener(v -> {
            String email = inputEmail.getText().toString().trim();
            if (TextUtils.isEmpty(email)) {
                Toast.makeText(this, "Insira o seu email.", Toast.LENGTH_SHORT).show();
                return;
            }
            mAuth.sendPasswordResetEmail(email).addOnSuccessListener(aVoid -> 
                Toast.makeText(this, "Email de recuperação enviado.", Toast.LENGTH_SHORT).show());
        });
    }

    private void handleAuth() {
        String email = inputEmail.getText().toString().trim();
        String password = inputPassword.getText().toString().trim();
        String name = inputName.getText().toString().trim();

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

        if (isLoginMode) {
            mAuth.signInWithEmailAndPassword(email, password)
                    .addOnSuccessListener(authResult -> {
                        startActivity(new Intent(this, ClientDashboardActivity.class));
                        finish();
                    })
                    .addOnFailureListener(e -> Toast.makeText(this, "Erro ao entrar: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        } else {
            if (TextUtils.isEmpty(name)) {
                Toast.makeText(this, "Insira o seu nome.", Toast.LENGTH_SHORT).show();
                return;
            }
            mAuth.createUserWithEmailAndPassword(email, password)
                    .addOnSuccessListener(authResult -> {
                        String uid = authResult.getUser().getUid();
                        User newUser = new User(uid, name, email, "CLIENTE");
                        db.collection("users").document(uid).set(newUser)
                                .addOnSuccessListener(aVoid -> {
                                    android.app.ActivityOptions options = android.app.ActivityOptions.makeCustomAnimation(this, android.R.anim.fade_in, android.R.anim.fade_out);
                                    startActivity(new Intent(this, ClientDashboardActivity.class), options.toBundle());
                                    finish();
                                });
                    })
                    .addOnFailureListener(e -> Toast.makeText(this, "Erro ao registar: " + e.getMessage(), Toast.LENGTH_SHORT).show());
        }
    }
}

