package com.example.cuida.ui.auth;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.cuida.MainActivity;
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.ActivityLoginBinding;
import com.example.cuida.R;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class LoginActivity extends AppCompatActivity {
    // gvjhbk
    private ActivityLoginBinding binding;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();

        // Check if user is already logged in
        // Check if user is already logged in and wants to be remembered
        SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
        boolean isLoggedIn = prefs.getBoolean("is_logged_in", false);
        boolean rememberMe = prefs.getBoolean("remember_me", false);

        if (isLoggedIn && rememberMe) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
            return;
        }

        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.loginButton.setOnClickListener(v -> login());
        binding.registerLink.setOnClickListener(v -> {
            startActivity(new Intent(this, RegisterActivity.class));
            finish();
        });

        binding.forgotPasswordLink.setOnClickListener(v -> {
            startActivity(new Intent(this, ForgotPasswordActivity.class));
        });
    }

    private void login() {
        String email = binding.emailEditText.getText().toString();
        String password = binding.passwordEditText.getText().toString();

        if (email.equals("admin") && password.equals("123")) {
            SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
            prefs.edit().putBoolean("is_logged_in", true).apply();
            // Mock data for admin
            String adminEmail = "admin@papcuida.com";
            prefs.edit().putString("user_email", adminEmail).apply();
            prefs.edit().putString("user_name", "Administrador").apply();

            // Ensure admin exists in DB
            UserDao userDao = AppDatabase.getDatabase(this).userDao();
            AppDatabase.databaseWriteExecutor.execute(() -> {
                if (userDao.checkUser(adminEmail) == null) {
                    User adminUser = new User("Administrador", adminEmail, "123", 99, "000000000");
                    // Set empty profile picture URI if needed to avoid null issues later, though
                    // it's optional
                    userDao.insert(adminUser);
                }
            });

            Toast.makeText(this, "Login de Administrador", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, MainActivity.class));
            finish();
            return;
        }

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

        binding.loginButton.setEnabled(false);
        binding.loginButton.setText("A entrar...");

        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, task -> {
                    binding.loginButton.setEnabled(true);
                    binding.loginButton.setText(R.string.login_button);

                    if (task.isSuccessful()) {
                        // Sign in success
                        FirebaseUser user = mAuth.getCurrentUser();

                        SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
                        boolean rememberMe = binding.checkboxRememberMe.isChecked();

                        prefs.edit().putBoolean("is_logged_in", true).apply();
                        prefs.edit().putBoolean("remember_me", rememberMe).apply();

                        // We can save user email/name from FirebaseUser if needed
                        if (user != null) {
                            prefs.edit().putString("user_email", user.getEmail()).apply();
                            String displayName = user.getDisplayName();
                            if (displayName != null) {
                                prefs.edit().putString("user_name", displayName).apply();
                            }
                        }

                        Toast.makeText(LoginActivity.this, "Bem-vindo!", Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        finish();
                    } else {
                        // If sign in fails, display a message to the user.
                        Toast.makeText(LoginActivity.this, "Falha na autenticação: " + task.getException().getMessage(),
                                Toast.LENGTH_SHORT).show();
                    }
                });
    }
}
