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

        // Inicializa o adapter
        adapter = new HistoryAdapter(requireContext());
        rvHistory.setAdapter(adapter);

        loadHistory();

        return root;
    }

    private void loadHistory() {
        // Recuperar o código do filho para isolamento de dados
        String childCode = requireContext().getSharedPreferences("FindU_Prefs", android.content.Context.MODE_PRIVATE)
                .getString("child_access_code", null);

        if (childCode == null || childCode.isEmpty()) {
            Log.e("FindU_Debug", "ERRO: childCode não encontrado no HistoryFragment.");
            return;
        }

        // MUDANÇA CRUCIAL: Agora buscamos na coleção "History"
        db.collection("History")
                .whereEqualTo("childCode", childCode)
                .orderBy("timestamp", Query.Direction.DESCENDING)
                .addSnapshotListener((value, error) -> {
                    if (error != null) {
                        Log.e("FindU_Debug", "Erro na Query History: " + error.getMessage());
                        return;
                    }

                    if (value != null) {
                        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);
                        }

                        // Envia a lista processada (com datas e eventos) para o adapter
                        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);

        SimpleDateFormat sdfBase = new SimpleDateFormat("dd MMMM", new Locale("pt", "PT"));

        if (targetCal.get(Calendar.YEAR) == todayCal.get(Calendar.YEAR) &&
                targetCal.get(Calendar.DAY_OF_YEAR) == todayCal.get(Calendar.DAY_OF_YEAR)) {
            return "Hoje, " + sdfBase.format(date);
        } else if (targetCal.get(Calendar.YEAR) == yesterdayCal.get(Calendar.YEAR) &&
                targetCal.get(Calendar.DAY_OF_YEAR) == yesterdayCal.get(Calendar.DAY_OF_YEAR)) {
            return "Ontem, " + sdfBase.format(date);
        } else {
            SimpleDateFormat sdfFull = new SimpleDateFormat("dd MMMM yyyy", new Locale("pt", "PT"));
            String f = sdfFull.format(date);
            return f.substring(0, 1).toUpperCase() + f.substring(1);
        }
    }

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