package com.example.pap_findu.ui.history;

import android.os.Bundle;
import android.util.Log;
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 androidx.recyclerview.widget.RecyclerView;

import com.example.pap_findu.adapters.HistoryAdapter;
import com.example.pap_findu.databinding.FragmentHistoryBinding;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class HistoryFragment extends Fragment {

    private FragmentHistoryBinding binding;
    private FirebaseFirestore db;
    private HistoryAdapter adapter;

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

        db = FirebaseFirestore.getInstance();

        RecyclerView rvHistory = binding.rvHistory;
        rvHistory.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new HistoryAdapter();
        rvHistory.setAdapter(adapter);

        loadHistory();

        return root;
    }

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

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

        if (childCode == null) {
            Log.e("FindU_Debug", "ERRO FATAL: childCode é nulo no HistoryFragment! 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
                        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) {
                        Log.d("FirebaseApp", "HistoryFragment -> Documentos recebidos: " + value.size());
                        List<Object> timelineList = new ArrayList<>();
                        String lastDateHeader = "";

                        for (QueryDocumentSnapshot doc : value) {
                            AlertMessage alert = doc.toObject(AlertMessage.class);
                            Date date = alert.getTimestamp();

                            if (date != null) {
                                String dateHeader = formatDateHeader(date);
                                if (!dateHeader.equals(lastDateHeader)) {
                                    timelineList.add(dateHeader);
                                    lastDateHeader = dateHeader;
                                }
                            }
                            timelineList.add(alert);
                        }

                        adapter.setItems(timelineList);
                    }
                });
    }

    private String formatDateHeader(Date date) {
        Calendar targetCal = Calendar.getInstance();
        targetCal.setTime(date);

        Calendar todayCal = Calendar.getInstance();
        
        Calendar yesterdayCal = Calendar.getInstance();
        yesterdayCal.add(Calendar.DAY_OF_YEAR, -1);

        if (targetCal.get(Calendar.YEAR) == todayCal.get(Calendar.YEAR) &&
            targetCal.get(Calendar.DAY_OF_YEAR) == todayCal.get(Calendar.DAY_OF_YEAR)) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM", new Locale("pt", "PT"));
            return "Hoje, " + sdf.format(date);
        } else if (targetCal.get(Calendar.YEAR) == yesterdayCal.get(Calendar.YEAR) &&
                   targetCal.get(Calendar.DAY_OF_YEAR) == yesterdayCal.get(Calendar.DAY_OF_YEAR)) {
            SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM", new Locale("pt", "PT"));
            return "Ontem, " + sdf.format(date);
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy", new Locale("pt", "PT"));
            // Capitalizar primeira letra no caso do MMMM ser retornado em minúsculo localmente
            String f = sdf.format(date);
            return f.substring(0, 1).toUpperCase() + f.substring(1);
        }
    }

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