package com.example.pap_findu.ui.alerts;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.widget.TextView;
import com.example.pap_findu.R;
import com.example.pap_findu.adapters.AlertsAdapter;
import com.example.pap_findu.databinding.FragmentAlertsBinding;
import com.example.pap_findu.models.AlertMessage;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QueryDocumentSnapshot;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AlertsFragment extends Fragment {

    private FragmentAlertsBinding binding;
    private AlertsAdapter adapter;
    private FirebaseFirestore db;
    private List<AlertMessage> allAlertsList = new ArrayList<>();
    private String currentFilter = "ALL";

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentAlertsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        db = FirebaseFirestore.getInstance();
        adapter = new AlertsAdapter(requireContext());
        
        binding.rvAlerts.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.rvAlerts.setAdapter(adapter);

        setupFilters();
        loadAlerts();

        return root;
    }

    private void setupFilters() {
        binding.filterAll.setOnClickListener(v -> applyFilter("ALL", binding.filterAll));
        binding.filterPending.setOnClickListener(v -> applyFilter("PENDING", binding.filterPending));
        binding.filterResolved.setOnClickListener(v -> applyFilter("RESOLVED", binding.filterResolved));
    }

    private void applyFilter(String filterType, TextView activeTextView) {
        currentFilter = filterType;

        // Reset visual state
        resetFilterStyles();

        // Set active style
        activeTextView.setBackgroundResource(R.drawable.bg_filter_chip_active);
        activeTextView.setTextColor(android.graphics.Color.parseColor("#1C6CFF"));

        filterAdapterList();
    }

    private void resetFilterStyles() {
        binding.filterAll.setBackgroundResource(R.drawable.bg_filter_chip_neutral);
        binding.filterAll.setTextColor(android.graphics.Color.parseColor("#64748B"));
        binding.filterPending.setBackgroundResource(R.drawable.bg_filter_chip_neutral);
        binding.filterPending.setTextColor(android.graphics.Color.parseColor("#64748B"));
        binding.filterResolved.setBackgroundResource(R.drawable.bg_filter_chip_neutral);
        binding.filterResolved.setTextColor(android.graphics.Color.parseColor("#64748B"));
    }

    private void loadAlerts() {
        // Isolamento de dados: só carregar alertas deste filho
        String childCode = requireContext().getSharedPreferences("FindU_Prefs", android.content.Context.MODE_PRIVATE)
                .getString("child_access_code", null);

        android.util.Log.d("FindU_Debug", "AlertsFragment -> childCode obtido: [" + childCode + "]");

        if (childCode == null) {
            android.util.Log.e("FindU_Debug", "ERRO FATAL: childCode é nulo no AlertsFragment! Verifique o registo do filho.");
            if (getContext() != null) {
                android.widget.Toast.makeText(getContext(), "Erro: Código do filho não encontrado.", android.widget.Toast.LENGTH_LONG).show();
            }
            return;
        }

        db.collection("Alerts")
          .whereEqualTo("childCode", childCode)
          .orderBy("timestamp", Query.Direction.DESCENDING)
          .addSnapshotListener((value, error) -> {
              if (error != null) {
                  // IMPORTANTE: O erro do Firestore contém o link para criar o índice no Logcat
                  android.util.Log.e("FindU_Debug", "Erro na Query: " + error.getMessage());
                  if (getActivity() != null) {
                      android.widget.Toast.makeText(getActivity(), "Erro de Base de Dados. Verifique o Logcat para o link do Índice.", android.widget.Toast.LENGTH_LONG).show();
                  }
                  return;
              }
              if (value != null) {
                  android.util.Log.d("FirebaseApp", "AlertsFragment -> Documentos recebidos: " + value.size());
                  allAlertsList.clear();
                  for (QueryDocumentSnapshot doc : value) {
                      AlertMessage alert = doc.toObject(AlertMessage.class);
                      allAlertsList.add(alert);
                  }
                  filterAdapterList();
                  updateAlertsSummary();
              }
          });
    }

    private void updateAlertsSummary() {
        if (binding == null) return;

        int pendingCount = 0;
        AlertMessage latestPending = null;

        for (AlertMessage msg : allAlertsList) {
            if ("PENDING".equals(msg.getStatus())) {
                pendingCount++;
                if (latestPending == null || (msg.getTimestamp() != null && latestPending.getTimestamp() != null && msg.getTimestamp().after(latestPending.getTimestamp()))) {
                    latestPending = msg;
                }
            }
        }

        // Referências diretas aos NOVOS IDs criados do zero
        View root = binding.getRoot();
        com.google.android.material.card.MaterialCardView bannerCard = root.findViewById(R.id.new_alert_banner);
        android.widget.ImageView iconView = root.findViewById(R.id.new_alert_icon);
        android.widget.TextView titleView = root.findViewById(R.id.new_alert_title);
        android.widget.TextView subtitleView = root.findViewById(R.id.new_alert_subtitle);

        if (bannerCard == null || iconView == null || titleView == null || subtitleView == null) {
            android.util.Log.e("AlertsFragment", "ERRO: Não foi possível encontrar os novos IDs do banner!");
            return;
        }

        bannerCard.setVisibility(View.VISIBLE);

        if (pendingCount > 0) {
            // --- ESTADO DE ATENÇÃO (Laranja) ---
            bannerCard.setCardBackgroundColor(android.graphics.Color.parseColor("#FFF3E0"));
            titleView.setText(pendingCount + " alerta(s) aguardando revisão");
            titleView.setTextColor(android.graphics.Color.parseColor("#E65100"));

            if (latestPending != null && latestPending.getTimestamp() != null) {
                subtitleView.setText("Último evento: " + getTimeAgo(latestPending.getTimestamp()));
            } else {
                subtitleView.setText("Verifique os detalhes abaixo.");
            }
            
            iconView.setImageResource(R.drawable.ic_alert_warning);
            iconView.clearColorFilter();
            iconView.setColorFilter(android.graphics.Color.parseColor("#E65100"), android.graphics.PorterDuff.Mode.SRC_IN);

        } else {
            // --- ESTADO SEGURO (Verde) ---
            bannerCard.setCardBackgroundColor(android.graphics.Color.parseColor("#E8F5E9"));
            titleView.setText("Tudo tranquilo");
            titleView.setTextColor(android.graphics.Color.parseColor("#2E7D32"));
            subtitleView.setText("Nenhum alerta pendente. Todos os eventos foram revistos.");
            
            iconView.setImageResource(android.R.drawable.ic_dialog_info);
            iconView.clearColorFilter();
            iconView.setColorFilter(android.graphics.Color.parseColor("#4CAF50"), android.graphics.PorterDuff.Mode.SRC_IN);
        }
    }

    private String getTimeAgo(Date date) {
        if (date == null) return "Desconhecido";
        long time = date.getTime();
        long now = System.currentTimeMillis();
        long diff = now - time;
        
        if (diff < 60000) return "Agora mesmo";
        else if (diff < 3600000) return "Há " + (diff / 60000) + " minuto(s)";
        else if (diff < 86400000) return "Há " + (diff / 3600000) + " hora(s)";
        else return "Há " + (diff / 86400000) + " dia(s)";
    }

    private void filterAdapterList() {
        if (currentFilter.equals("ALL")) {
            adapter.setAlertsList(new ArrayList<>(allAlertsList));
            return;
        }

        List<AlertMessage> filtered = new ArrayList<>();
        for (AlertMessage msg : allAlertsList) {
            if (currentFilter.equals(msg.getStatus())) {
                filtered.add(msg);
            }
        }
        adapter.setAlertsList(filtered);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
