package com.example.pap_findu;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.example.pap_findu.models.AlertMessage;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;

import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;

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

public class GeofenceBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = "GeofenceReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            Log.e(TAG, "Geofencing error: " + geofencingEvent.getErrorCode());
            return;
        }

        // Get the transition type
        int geofenceTransition = geofencingEvent.getGeofenceTransition();

        // Test that the reported transition was of interest
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT || geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
            
            // Get the geofences that were triggered
            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
            
            if (triggeringGeofences != null && !triggeringGeofences.isEmpty()) {
                String requestId = triggeringGeofences.get(0).getRequestId();

                FirebaseFirestore db = FirebaseFirestore.getInstance();
                FirebaseAuth auth = FirebaseAuth.getInstance();
                FirebaseUser user = auth.getCurrentUser();

                db.collection("SafeZones").document(requestId).get()
                        .addOnSuccessListener(documentSnapshot -> {
                            String zoneName = "Zona Desconhecida";
                            if (documentSnapshot.exists() && documentSnapshot.getString("name") != null) {
                                zoneName = documentSnapshot.getString("name");
                            }
                            salvarAlerta(context, db, user, geofenceTransition, zoneName);
                        })
                        .addOnFailureListener(e -> {
                            salvarAlerta(context, db, user, geofenceTransition, "Zona Desconhecida");
                        });
            }
        } else {
            Log.e(TAG, "GEOFENCE_TRANSITION INVALID TYPE: " + geofenceTransition);
        }
    }

    private void salvarAlerta(Context context, FirebaseFirestore db, FirebaseUser user, int geofenceTransition, String zoneName) {
        // TAREFA 1: Recuperar childCode das SharedPreferences com a mesma chave de isolamento
        String childCode = context.getSharedPreferences("FindU_Prefs", Context.MODE_PRIVATE)
                .getString("child_access_code", null);

        Log.d(TAG, "salvarAlerta -> childCode obtido: [" + childCode + "]");
        Log.d("FindU_Flow", "Gravando alerta para o código: " + childCode);

        if (childCode == null || childCode.isEmpty() || childCode.equals("Unknown")) {
            Log.e(TAG, "ERRO: O filho tentou gerar um alerta mas o childCode é nulo/vazio! Alerta NÃO gravado.");
            return; // Não grava o alerta órfão
        }

        String docId = db.collection("Alerts").document().getId();

        String type;
        String status;
        String title;
        String message;

        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
            type = "URGENT";
            status = "PENDING";
            title = "Saída da Zona Segura";
            message = "O filho saiu da zona: " + zoneName;
        } else {
            type = "INFO";
            status = "RESOLVED";
            title = "Entrada na Zona Segura";
            message = "O filho entrou na zona: " + zoneName;
        }

        // OBRIGATÓRIO: Usar HashMap para garantir que childCode está presente no documento
        Map<String, Object> alertData = new HashMap<>();
        alertData.put("id", docId);
        alertData.put("title", title);
        alertData.put("message", message);
        alertData.put("timestamp", new Date());
        alertData.put("type", type);
        alertData.put("status", status);
        alertData.put("childCode", childCode); // OBRIGATÓRIO: campo de isolamento

        db.collection("Alerts").document(docId).set(alertData)
                .addOnSuccessListener(aVoid -> {
                    Log.d(TAG, "✅ Alerta gravado com SUCESSO. docId=" + docId + ", childCode=" + childCode);
                    Log.d("FindU_Flow", "Alerta gravado: docId=" + docId + " | childCode=" + childCode + " | type=" + type);
                })
                .addOnFailureListener(e -> {
                    Log.e(TAG, "❌ ERRO ao gravar alerta: " + e.getMessage(), e);
                    Log.e("FindU_Flow", "Falha ao gravar alerta para childCode=" + childCode + ": " + e.getMessage());
                });

        Log.w(TAG, message);
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }
}
