package com.example.pap_findu;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

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

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.button.MaterialButton;
import com.google.firebase.Timestamp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class login_activity extends AppCompatActivity {

    private EditText emailEditText;
    private EditText passwordEditText;
    private Button btnLogin;
    private TextView criarContaTextView;

    private MaterialButton btnChildLogin;
    private FirebaseFirestore db;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.login_activity);

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

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

        emailEditText = findViewById(R.id.emailEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        btnLogin = findViewById(R.id.btnLogin);
        criarContaTextView = findViewById(R.id.criarContaTextView);
        btnChildLogin = findViewById(R.id.btnChildLogin);

        btnLogin.setOnClickListener(v -> {
            String email = emailEditText.getText().toString();
            String password = passwordEditText.getText().toString();

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

            mAuth.signInWithEmailAndPassword(email, password)
                    .addOnCompleteListener(login_activity.this, task -> {
                        if (task.isSuccessful()) {
                            Toast.makeText(login_activity.this, "Login com sucesso.", Toast.LENGTH_SHORT).show();
                            goToMainActivity();
                        } else {
                            Toast.makeText(login_activity.this, "Falha na autenticação.", Toast.LENGTH_SHORT).show();
                        }
                    });
        });

        btnChildLogin.setOnClickListener(v -> showChildLoginDialog());

        criarContaTextView.setOnClickListener(v -> {
            Intent intent = new Intent(login_activity.this, CriarConta.class);
            startActivity(intent);
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if(currentUser != null){
            goToMainActivity();
        }
    }

    private void goToMainActivity() {
        Intent intent = new Intent(login_activity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    private void showChildLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Acesso do Filho");
        builder.setMessage("Digite o código de 6 dígitos gerado pelo pai:");

        final EditText inputCode = new EditText(this);
        inputCode.setInputType(InputType.TYPE_CLASS_NUMBER);
        inputCode.setHint("Ex: 123456");
        builder.setView(inputCode);

        builder.setPositiveButton("Entrar", (dialog, which) -> {
            String code = inputCode.getText().toString().trim();
            if (!TextUtils.isEmpty(code)) {
                verifyChildCode(code);
            } else {
                Toast.makeText(login_activity.this, "Código vazio.", Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton("Cancelar", (dialog, which) -> dialog.cancel());
        builder.show();
    }

    private void verifyChildCode(String code) {
        db.collection("login_codes").document(code).get()
                .addOnSuccessListener(document -> {
                    if (document.exists()) {
                        boolean used = Boolean.TRUE.equals(document.getBoolean("used"));
                        Timestamp expiresAt = document.getTimestamp("expiresAt");

                        if (used) {
                            Toast.makeText(this, "Este código já foi usado.", Toast.LENGTH_LONG).show();
                            return;
                        }
                        if (expiresAt != null && expiresAt.toDate().before(new Date())) {
                            Toast.makeText(this, "O código expirou.", Toast.LENGTH_LONG).show();
                            return;
                        }

                        // SUCESSO: O código é bom!
                        String parentId = document.getString("parentId");
                        String childName = document.getString("childName");

                        // =======================================================
                        // ASSOCIAÇÃO AUTOMÁTICA: Cria o registo na coleção 'children'
                        // =======================================================
                        Map<String, Object> childData = new HashMap<>();
                        childData.put("parentId", parentId);
                        childData.put("accessCode", code);
                        childData.put("name", childName != null ? childName : "Filho");
                        childData.put("createdAt", new Timestamp(new Date()));

                        db.collection("children").document(code).set(childData)
                                .addOnSuccessListener(aVoid -> loginChildAnonymously(code, parentId))
                                .addOnFailureListener(e -> Toast.makeText(this, "Erro ao associar filho.", Toast.LENGTH_SHORT).show());

                    } else {
                        Toast.makeText(this, "Código inválido.", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(e -> Toast.makeText(this, "Erro de conexão.", Toast.LENGTH_SHORT).show());
    }

    private void loginChildAnonymously(String code, String parentId) {
        mAuth.signInAnonymously()
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        // Invalida o código no Firestore
                        db.collection("login_codes").document(code).update("used", true);

                        // Guarda o código para o LocationService usar
                        getSharedPreferences("FindU_Prefs", MODE_PRIVATE)
                                .edit()
                                .putString("child_access_code", code)
                                .apply();

                        Toast.makeText(this, "Conectado como Filho!", Toast.LENGTH_SHORT).show();
                        goToMainActivity();
                    } else {
                        Toast.makeText(this, "Erro no login anônimo.", Toast.LENGTH_SHORT).show();
                    }
                });
    }
}