package com.example.pap_findu.ui.zones;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
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.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
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 String currentChildId = null;
    private String currentChildName = "Filho";

    private DatabaseReference locationRef;
    private ValueEventListener locationListener;
    private com.google.firebase.firestore.ListenerRegistration safeZonesListener;

    private Location childLocation = null;
    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);
                    checkSafetyStatus();
                }
            });
        }

        checkUserChildren();

        return root;
    }

    private void checkUserChildren() {
        FirebaseUser user = auth.getCurrentUser();
        if (user == null) return;

        if (user.isAnonymous()) {
            currentChildId = requireContext().getSharedPreferences("FindU_Prefs", android.content.Context.MODE_PRIVATE)
                    .getString("child_access_code", null);
            currentChildName = "Você";
            if (currentChildId != null) {
                listenToChildLocation();
            }
            return;
        }

        db.collection("children")
                .whereEqualTo("parentId", user.getUid())
                .limit(1)
                .get()
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful() && task.getResult() != null && !task.getResult().isEmpty()) {
                        DocumentSnapshot document = task.getResult().getDocuments().get(0);
                        currentChildId = document.getString("accessCode");

                        if (document.contains("name")) {
                            currentChildName = document.getString("name");
                        } else if (document.contains("nome")) {
                            currentChildName = document.getString("nome");
                        }

                        if (currentChildId != null) {
                            listenToChildLocation();
                        }
                    }
                });
    }

    private void listenToChildLocation() {
        locationRef = FirebaseDatabase.getInstance().getReference(currentChildId).child("live_location");
        locationListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()) {
                    Double lat = snapshot.child("latitude").getValue(Double.class);
                    Double lng = snapshot.child("longitude").getValue(Double.class);
                    if (lat != null && lng != null) {
                        childLocation = new Location("");
                        childLocation.setLatitude(lat);
                        childLocation.setLongitude(lng);
                        checkSafetyStatus();
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {}
        };
        locationRef.addValueEventListener(locationListener);
    }

    private void checkSafetyStatus() {
        if (childLocation == null || binding == null || safeZonesList == null) return;

        boolean isSafe = false;

        for (DocumentSnapshot zoneDoc : safeZonesList) {
            Double lat = zoneDoc.getDouble("latitude");
            Double lng = zoneDoc.getDouble("longitude");
            if (lat != null && lng != null) {
                Location zoneLocation = new Location("");
                zoneLocation.setLatitude(lat);
                zoneLocation.setLongitude(lng);

                if (childLocation.distanceTo(zoneLocation) <= 200.0) {
                    isSafe = true;
                    break;
                }
            }
        }

        updateUIBanner(isSafe);
    }

    private void updateUIBanner(boolean isSafe) {
        View root = binding.getRoot();
        LinearLayout bannerLayout = root.findViewById(R.id.bannerZoneLayout);
        TextView title = root.findViewById(R.id.bannerZoneTitle);
        TextView subtitle = root.findViewById(R.id.bannerZoneSubtitle);

        if (bannerLayout == null || title == null || subtitle == null) return;

        GradientDrawable background = (GradientDrawable) bannerLayout.getBackground().mutate();

        if (isSafe) {
            // VERDE -> Seguro
            background.setColor(Color.parseColor("#EAF4D4")); // Fundo verde clarinho
            title.setTextColor(Color.parseColor("#0B6635"));
            subtitle.setTextColor(Color.parseColor("#0B6635"));

            title.setText("O " + currentChildName + " está numa zona segura");
            subtitle.setText("A rotina tem estado estável.");
        } else {
            // LARANJA -> Fora da zona
            background.setColor(Color.parseColor("#FFE0B2")); // Fundo laranja clarinho
            title.setTextColor(Color.parseColor("#E65100"));
            subtitle.setTextColor(Color.parseColor("#E65100"));

            title.setText("Atenção: Fora de zona segura");
            subtitle.setText("O " + currentChildName + " movimentou-se para fora de contexto.");
        }
    }

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