package com.example.pap_findu.ui.zones;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

import com.example.pap_findu.R;
import com.example.pap_findu.adapters.ZonesAdapter;
import com.example.pap_findu.databinding.FragmentZonesBinding;
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.ArrayList;
import java.util.List;

public class ZonesFragment extends Fragment {

    private FragmentZonesBinding binding;
    private FirebaseAuth auth;
    private FirebaseFirestore db;

    private com.google.firebase.firestore.ListenerRegistration safeZonesListener;
    private List<DocumentSnapshot> safeZonesList = new ArrayList<>();

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

        auth = FirebaseAuth.getInstance();
        db = FirebaseFirestore.getInstance();

        boolean isChild = false;
        FirebaseUser user = auth.getCurrentUser();
        if (user != null && user.isAnonymous()) {
            isChild = true;
            binding.addZoneButton.setVisibility(View.GONE);
        }

        binding.addZoneButton.setOnClickListener(v -> {
            android.content.Intent intent = new android.content.Intent(getContext(),
                    com.example.pap_findu.AddZoneActivity.class);
            startActivity(intent);
        });

        ZonesAdapter adapter = new ZonesAdapter();
        adapter.setChildMode(isChild);
        binding.recyclerViewZones.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerViewZones.setAdapter(adapter);

        // Isolamento de dados: só carregar zonas deste filho
        String childCode = requireContext().getSharedPreferences("FindU_Prefs", android.content.Context.MODE_PRIVATE)
                .getString("child_access_code", null);
        if (childCode != null) {
            safeZonesListener = db.collection("SafeZones")
                    .whereEqualTo("childCode", childCode)
                    .addSnapshotListener((value, error) -> {
                if (error != null) {
                    Log.e("ZonesFragment", "Erro ao carregar zonas", error);
                    return;
                }
                if (value != null) {
                    safeZonesList = value.getDocuments();
                    adapter.setZonesList(safeZonesList);

                    // Atualizar contador dinâmico de zonas
                    if (isAdded() && getActivity() != null && binding != null) {
                        int count = value.size();
                        TextView tvZoneCount = binding.getRoot().findViewById(R.id.tvDynamicZoneCount);
                        if (tvZoneCount != null) {
                            if (count == 0) {
                                tvZoneCount.setText("Nenhuma zona segura criada");
                            } else if (count == 1) {
                                tvZoneCount.setText("1 zona monitorizada");
                            } else {
                                tvZoneCount.setText(count + " zonas monitorizadas");
                            }
                        }
                    }
                }
            });
        }

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (safeZonesListener != null) {
            safeZonesListener.remove();
        }
        binding = null;
    }
}
