package com.example.pap_findu;

import android.content.Intent;
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.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.Date;

public class login_activity extends AppCompatActivity {

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

    // --- NOVAS VARIÁVEIS PARA O FILHO ---
    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;
        });

        // Inicializar Firebase Auth e Firestore
        mAuth = FirebaseAuth.getInstance();
        db = FirebaseFirestore.getInstance();

        // Vincular componentes
        emailEditText = findViewById(R.id.emailEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        btnLogin = findViewById(R.id.btnLogin);
        criarContaTextView = findViewById(R.id.criarContaTextView);

        // Novo botão do filho (Certifique-se que adicionou no XML com id btnChildLogin)
        btnChildLogin = findViewById(R.id.btnChildLogin);

        // --- LÓGICA 1: LOGIN DO PAI (Seu código original) ---
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View 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, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> 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();
                                }
                            }
                        });
            }
        });

        // --- LÓGICA 2: LOGIN DO FILHO (Novo código) ---
        btnChildLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showChildLoginDialog();
            }
        });

        // --- LÓGICA 3: CRIAR CONTA ---
        criarContaTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(login_activity.this, CriarConta.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        // Verifica se já está logado
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if(currentUser != null){
            goToMainActivity();
        }
    }

    private void goToMainActivity() {
        Intent intent = new Intent(login_activity.this, MainActivity.class);
        // Limpa a pilha para não voltar ao login com o botão voltar
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    // ==========================================================
    // MÉTODOS DE LOGIN DO FILHO
    // ==========================================================

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

        // Cria uma caixa de texto dentro do alerta
        final EditText inputCode = new EditText(this);
        inputCode.setInputType(InputType.TYPE_CLASS_NUMBER);
        inputCode.setHint("Ex: 123456");
        builder.setView(inputCode);

        // Botão Entrar do Alerta
        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) {
        // Verifica no Firestore se o código existe
        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");

                        // Validações
                        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");
                        loginChildAnonymously(code, parentId);

                    } 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) {
        // Faz login anônimo (sem email)
        mAuth.signInAnonymously()
                .addOnCompleteListener(this, task -> {
                    if (task.isSuccessful()) {
                        // 1. Invalida o código para ninguém usar de novo
                        db.collection("login_codes").document(code).update("used", true);

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