package com.example.cuida.ui.auth;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.cuida.MainActivity;
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;
import androidx.biometric.BiometricPrompt;
import androidx.biometric.BiometricManager;
import androidx.core.content.ContextCompat;
import java.util.concurrent.Executor;

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 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) {
            if (mAuth.getCurrentUser() != null) {
                startActivity(new Intent(this, MainActivity.class));
                finish();
                return;
            }
        } else {
            // Se não for para lembrar a sessão, garantimos que o estado de login é falso
            // mas NÃO limpamos as credenciais guardadas para a biometria.
            if (mAuth.getCurrentUser() != null) {
                mAuth.signOut();
            }
            prefs.edit().putBoolean("is_logged_in", false).apply();
        }

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



        setupBiometrics();
    }

    private void setupBiometrics() {
        BiometricManager biometricManager = BiometricManager.from(this);
        int canAuthenticate = biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG | BiometricManager.Authenticators.DEVICE_CREDENTIAL);
        
        SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
        String savedEmail = prefs.getString("saved_email", null);
        String savedPass = prefs.getString("saved_pass", null);

        if (canAuthenticate == BiometricManager.BIOMETRIC_SUCCESS && savedEmail != null && savedPass != null) {
            binding.biometricButton.setVisibility(android.view.View.VISIBLE);
            binding.biometricButton.setOnClickListener(v -> showBiometricPrompt(savedEmail, savedPass));
        }
    }

    private void showBiometricPrompt(String email, String pass) {
        Executor executor = ContextCompat.getMainExecutor(this);
        BiometricPrompt biometricPrompt = new BiometricPrompt(LoginActivity.this, executor, new BiometricPrompt.AuthenticationCallback() {
            @Override
            public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) {
                super.onAuthenticationError(errorCode, errString);
            }

            @Override
            public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) {
                super.onAuthenticationSucceeded(result);
                // Perform login with saved credentials
                loginWithSavedCredentials(email, pass);
            }

            @Override
            public void onAuthenticationFailed() {
                super.onAuthenticationFailed();
            }
        });

        BiometricPrompt.PromptInfo promptInfo = new BiometricPrompt.PromptInfo.Builder()
                .setTitle("Autenticação Biométrica")
                .setSubtitle("Entre na sua conta usando biometria")
                .setNegativeButtonText("Usar Password")
                .build();

        biometricPrompt.authenticate(promptInfo);
    }

    private void loginWithSavedCredentials(String email, String pass) {
        if (!isNetworkAvailable()) {
            Toast.makeText(this, "Sem ligação à internet. Verifique a sua rede e tente novamente.", Toast.LENGTH_LONG).show();
            return;
        }

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

        mAuth.signInWithEmailAndPassword(email, pass)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        FirebaseUser user = mAuth.getCurrentUser();
                        if (user != null) {
                            handleSuccessfulAuth(user, email, pass, true);
                        }
                    } else {
                        binding.loginButton.setEnabled(true);
                        binding.loginButton.setText(R.string.login_button);
                        String errorMsg = traduzirErroFirebase(task.getException());
                        Toast.makeText(this, "Erro: " + errorMsg, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) return false;
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnected();
    }

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

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

        if (!isNetworkAvailable()) {
            Toast.makeText(this, "Sem internet.", Toast.LENGTH_SHORT).show();
            return;
        }

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

        mAuth.signInWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        FirebaseUser user = mAuth.getCurrentUser();
                        if (user != null) {
                            boolean rememberMe = binding.checkboxRememberMe.isChecked();
                            handleSuccessfulAuth(user, email, password, rememberMe);
                        }
                    } else {
                        binding.loginButton.setEnabled(true);
                        binding.loginButton.setText(R.string.login_button);

                        String errorMsg = traduzirErroFirebase(task.getException());
                        Toast.makeText(LoginActivity.this, errorMsg, Toast.LENGTH_LONG).show();
                    }
                });
    }

    private String traduzirErroFirebase(Exception exception) {
        if (exception == null) return "Erro desconhecido.";

        String className = exception.getClass().getSimpleName();
        if (className.contains("Network") || className.contains("IOException")) {
            return "Sem internet.";
        }

        String msg = exception.getMessage();
        if (msg == null) return "Erro desconhecido.";

        if (msg.contains("NETWORK_REQUEST_FAILED") || msg.contains("network error")
                || msg.contains("network") || msg.contains("Network")) {
            return "Sem internet.";
        } else if (msg.contains("invalid credential") || msg.contains("password is invalid")
                || msg.contains("There is no user record") || msg.contains("INVALID_LOGIN_CREDENTIALS")) {
            return "Credenciais erradas.";
        } else if (msg.contains("badly formatted")) {
            return "Email inválido.";
        } else if (msg.contains("too many requests") || msg.contains("TOO_MANY_ATTEMPTS_TRY_LATER")) {
            return "Tente mais tarde.";
        } else if (msg.contains("user disabled") || msg.contains("USER_DISABLED")) {
            return "Conta desativada.";
        }

        return "Erro ao entrar.";
    }

    private void handleSuccessfulAuth(FirebaseUser user, String email, String password, boolean rememberMe) {
        SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
        prefs.edit().putBoolean("is_logged_in", true).apply();
        prefs.edit().putBoolean("remember_me", rememberMe).apply();
        
        // Guardar sempre para biometria após login com sucesso
        prefs.edit().putString("saved_email", email).apply();
        prefs.edit().putString("saved_pass", password).apply();

        // Tentar primeiro na coleção 'utilizadores'
        com.google.firebase.firestore.FirebaseFirestore db = com.google.firebase.firestore.FirebaseFirestore.getInstance();
        db.collection("utilizadores").document(user.getUid()).get()
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful() && task.getResult() != null && task.getResult().exists()) {
                        com.google.firebase.firestore.DocumentSnapshot doc = task.getResult();
                        String name = doc.getString("name");
                        String dbEmail = doc.getString("email");
                        
                        if (name != null) prefs.edit().putString("user_name", name).apply();
                        if (dbEmail != null) prefs.edit().putString("user_email", dbEmail).apply();
                        
                        proceedToMain();
                    } else {
                        // Tentar na coleção 'medicos'
                        db.collection("medicos").document(user.getUid()).get()
                                .addOnCompleteListener(task2 -> {
                                    if (task2.isSuccessful() && task2.getResult() != null && task2.getResult().exists()) {
                                        com.google.firebase.firestore.DocumentSnapshot doc = task2.getResult();
                                        String name = doc.getString("nome"); // Notar campo 'nome' em vez de 'name'
                                        String dbEmail = doc.getString("email");
                                        
                                        if (name != null) prefs.edit().putString("user_name", name).apply();
                                        if (dbEmail != null) prefs.edit().putString("user_email", dbEmail).apply();
                                        
                                        proceedToMain();
                                    } else {
                                        // Fallback se não encontrar em lado nenhum
                                        prefs.edit().putString("user_email", user.getEmail()).apply();
                                        if (user.getDisplayName() != null && !user.getDisplayName().isEmpty()) {
                                            prefs.edit().putString("user_name", user.getDisplayName()).apply();
                                        } else {
                                            String authEmail = user.getEmail();
                                            if (authEmail != null && authEmail.contains("@")) {
                                                String fallbackName = authEmail.substring(0, authEmail.indexOf("@"));
                                                prefs.edit().putString("user_name", fallbackName).apply();
                                            }
                                        }
                                        proceedToMain();
                                    }
                                });
                    }
                });
    }

    private void proceedToMain() {
        Toast.makeText(LoginActivity.this, "Bem-vindo!", Toast.LENGTH_SHORT).show();
        startActivity(new Intent(LoginActivity.this, com.example.cuida.MainActivity.class));
        finish();
    }
}
