package com.example.pap_findu.ui.map;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.pap_findu.ChatActivity;
import com.example.pap_findu.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
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;

public class MapFragment extends Fragment implements OnMapReadyCallback {

    private Button btnAddChild;
    private View layoutEmptyState;
    private View mapContainer;
    private FirebaseFirestore db;
    private FirebaseAuth auth;

    private FloatingActionButton btnAbrirChat;
    private FloatingActionButton btnCenterMap;
    private MaterialButton btnSOS;

    // --- VARIÁVEIS PARA O CARTÃO DE INFORMAÇÃO PREMIUM ---
    private View cardChildInfo;
    private TextView txtChildName;
    private TextView txtChildBattery;

    // --- VARIÁVEIS PARA A ZONA DE STATUS (VERDE/LARANJA) ---
    private MaterialCardView cardZoneStatus, cardZoneIconBG;
    private ImageView iconZone;
    private TextView txtZoneTitle, txtZoneSubtitle;

    private GoogleMap mMap;
    private Marker childMarker;
    private DatabaseReference locationRef;
    private ValueEventListener locationListener;

    private String currentChildId = null;

    // NOVA VARIÁVEL: Guarda o nome real do filho
    private String currentChildName = "A carregar...";
    private LatLng lastChildLocation;

    private com.google.firebase.firestore.ListenerRegistration safeZonesListener;
    private java.util.List<com.google.android.gms.maps.model.Circle> mapCircles = new java.util.ArrayList<>();

    private static class SafeZoneData {
        String name;
        double latitude;
        double longitude;
        double radius;
    }
    private java.util.List<SafeZoneData> safeZonesList = new java.util.ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_map, container, false);

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

        layoutEmptyState = root.findViewById(R.id.layoutEmptyState);
        mapContainer = root.findViewById(R.id.mapContainer);
        btnAddChild = root.findViewById(R.id.btnAddChild);
        btnAbrirChat = root.findViewById(R.id.btnAbrirChat);
        btnSOS = root.findViewById(R.id.btnSOS);

        // --- INICIALIZAR AS VIEWS DO CARTÃO ---
        cardChildInfo = root.findViewById(R.id.cardChildInfo);
        txtChildName = root.findViewById(R.id.txtChildName);
        txtChildBattery = root.findViewById(R.id.txtChildBattery);

        // --- INICIALIZAR AS VIEWS DA ZONA ---
        cardZoneStatus = root.findViewById(R.id.cardZoneStatus);
        cardZoneIconBG = root.findViewById(R.id.cardZoneIconBG);
        iconZone = root.findViewById(R.id.iconZone);
        txtZoneTitle = root.findViewById(R.id.txtZoneTitle);
        txtZoneSubtitle = root.findViewById(R.id.txtZoneSubtitle);
        btnCenterMap = root.findViewById(R.id.btnCenterMap);

        if (btnCenterMap != null) {
            btnCenterMap.setOnClickListener(v -> centerOnChildLocation());
        }

        if (btnAbrirChat != null) btnAbrirChat.setVisibility(View.GONE);
        if (btnSOS != null) btnSOS.setVisibility(View.GONE);
        if (cardChildInfo != null) cardChildInfo.setVisibility(View.GONE); // Começa escondido

        if (btnAddChild != null) {
            btnAddChild.setOnClickListener(v -> openAddChildScreen());
        }

        checkUserTypeAndShowScreen();

        return root;
    }

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

        if (user.isAnonymous()) {
            showMapState();
            setupChildButtons();
        } else {
            checkIfHasChildren();
        }
    }

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

        db.collection("children")
                .whereEqualTo("parentId", user.getUid())
                .limit(1)
                .get()
                .addOnCompleteListener(task -> {
                    if (task.isSuccessful() && task.getResult() != null && !task.getResult().isEmpty()) {

                        // Extraímos o documento todo
                        DocumentSnapshot document = task.getResult().getDocuments().get(0);
                        currentChildId = document.getString("accessCode");

                        // LER O NOME REAL DA BASE DE DADOS FIRESTORE
                        if (document.contains("name")) {
                            currentChildName = document.getString("name");
                        } else if (document.contains("nome")) {
                            currentChildName = document.getString("nome");
                        } else {
                            currentChildName = "Filho";
                        }

                        if (currentChildId != null) {
                            // Guardar childCode em SharedPreferences para uso em outros fragments
                            requireContext().getSharedPreferences("FindU_Prefs", Context.MODE_PRIVATE)
                                    .edit().putString("child_access_code", currentChildId).apply();
                            showMapState();
                            setupChildButtons();
                            if (mMap != null) {
                                startListeningToChildLocation();
                            }
                        } else {
                            showEmptyState();
                        }
                    } else {
                        showEmptyState();
                    }
                });
    }

    private void setupChildButtons() {
        if (btnAbrirChat != null) {
            btnAbrirChat.setVisibility(View.VISIBLE);
            btnAbrirChat.setOnClickListener(v -> {
                String roomCode = auth.getCurrentUser().isAnonymous() ?
                        requireContext().getSharedPreferences("FindU_Prefs", Context.MODE_PRIVATE).getString("child_access_code", null) :
                        currentChildId;

                if (roomCode != null) {
                    requireContext().getSharedPreferences("FindU_Prefs", Context.MODE_PRIVATE).edit().putString("child_access_code", roomCode).apply();
                    startActivity(new Intent(getActivity(), ChatActivity.class));
                }
            });
        }
        if (btnSOS != null) {
            btnSOS.setVisibility(View.VISIBLE);
            btnSOS.setOnClickListener(v -> {
                Intent sosIntent = new Intent(Intent.ACTION_DIAL);
                sosIntent.setData(Uri.parse("tel:112"));
                startActivity(sosIntent);
            });
        }
    }

    private void showMapState() {
        if (layoutEmptyState != null) layoutEmptyState.setVisibility(View.GONE);
        if (mapContainer != null) mapContainer.setVisibility(View.VISIBLE);

        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapContainer);
        if (mapFragment != null) {
            mapFragment.getMapAsync(this);
        }
    }

    @Override
    public void onMapReady(@NonNull GoogleMap googleMap) {
        mMap = googleMap;
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
        FirebaseUser user = auth.getCurrentUser();

        if (user != null && user.isAnonymous()) {
            if (androidx.core.content.ContextCompat.checkSelfPermission(requireContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                mMap.setMyLocationEnabled(true);
                com.google.android.gms.location.FusedLocationProviderClient fusedLocationClient = com.google.android.gms.location.LocationServices.getFusedLocationProviderClient(requireActivity());
                fusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
                    if (location != null && mMap != null) {
                        mMap.moveCamera(com.google.android.gms.maps.CameraUpdateFactory.newLatLngZoom(
                                new com.google.android.gms.maps.model.LatLng(location.getLatitude(), location.getLongitude()), 16f));
                    }
                });
            }
        } else {
            if (currentChildId != null) {
                startListeningToChildLocation();
            } else {
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(0, 0), 2f));
            }
        }
    }

    private void startListeningToChildLocation() {
        if (currentChildId == null || mMap == null) return;

        FirebaseUser user = auth.getCurrentUser();

        // SE FOR O PAI, MOSTRAMOS O CARTÃO DO FILHO
        if (user != null && !user.isAnonymous()) {
            if (cardChildInfo != null) cardChildInfo.setVisibility(View.VISIBLE);

            // CORREÇÃO: Agora usa estritamente o nome lido da base de dados (Ex: "Jorge")
            if (txtChildName != null) {
                txtChildName.setText(currentChildName);
            }
        }

        locationRef = FirebaseDatabase.getInstance().getReference(currentChildId).child("live_location");
        if (locationListener != null) locationRef.removeEventListener(locationListener);

        locationListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists() && mMap != null) {
                    Double lat = snapshot.child("latitude").getValue(Double.class);
                    Double lng = snapshot.child("longitude").getValue(Double.class);

                    // LÊ A BATERIA DO FIREBASE
                    String bateria = snapshot.child("bateria").getValue(String.class);

                    // ATUALIZA O TEXTO DA BATERIA
                    if (bateria != null && txtChildBattery != null) {
                        txtChildBattery.setText(bateria);
                    }

                    if (lat != null && lng != null) {
                        lastChildLocation = new LatLng(lat, lng);
                        LatLng childPos = new LatLng(lat, lng);

                        if (Math.abs(lat - 37.4219) > 0.001) {
                            if (childMarker == null) {
                                childMarker = mMap.addMarker(new MarkerOptions()
                                        .position(childPos)
                                        .title(currentChildName) // O pino no mapa também vai dizer o nome do filho
                                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
                            } else {
                                childMarker.setPosition(childPos);
                                childMarker.setTitle(currentChildName);
                            }
                            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(childPos, 17f));

                            android.location.Location childLoc = new android.location.Location("child");
                            childLoc.setLatitude(lat);
                            childLoc.setLongitude(lng);
                            if (getActivity() != null) {
                                getActivity().runOnUiThread(() -> updateSafetyStatusBanner(childLoc));
                            }
                        }
                    }
                }
            }
            @Override public void onCancelled(@NonNull DatabaseError error) {}
        };
        locationRef.addValueEventListener(locationListener);

        // Listener de SafeZones filtrado por childCode
        String childCode = requireContext().getSharedPreferences("FindU_Prefs", Context.MODE_PRIVATE)
                .getString("child_access_code", null);
        if (safeZonesListener != null) safeZonesListener.remove();
        if (childCode == null) return;
        safeZonesListener = db.collection("SafeZones")
                .whereEqualTo("childCode", childCode)
                .addSnapshotListener((value, error) -> {
            if (error != null || value == null || mMap == null) return;

            // Limpa circulos velhos
            for (com.google.android.gms.maps.model.Circle circle : mapCircles) {
                if (circle != null) circle.remove();
            }
            mapCircles.clear();
            safeZonesList.clear();

            for (DocumentSnapshot doc : value.getDocuments()) {
                Double lat = doc.getDouble("latitude");
                Double lng = doc.getDouble("longitude");
                Double radius = doc.getDouble("radius");
                String name = doc.getString("name");

                if (lat != null && lng != null) {
                    SafeZoneData sz = new SafeZoneData();
                    sz.name = name != null ? name : "Zona";
                    sz.latitude = lat;
                    sz.longitude = lng;
                    sz.radius = radius != null ? radius : 200.0;
                    safeZonesList.add(sz);

                    LatLng latLng = new LatLng(lat, lng);
                    com.google.android.gms.maps.model.Circle circle = mMap.addCircle(new com.google.android.gms.maps.model.CircleOptions()
                            .center(latLng)
                            .radius(sz.radius)
                            .strokeColor(0xFF006400) // Verde escuro
                            .fillColor(0x3300FF00) // Verde semi-transparente
                            .strokeWidth(5f));
                    mapCircles.add(circle);
                }
            }
        });
    }

    private void updateSafetyStatusBanner(android.location.Location childLocation) {
        if (safeZonesList.isEmpty()) {
            atualizarStatusZona(false, "Nenhuma zona segura definida");
            return;
        }

        boolean insideAnyZone = false;
        String insideZoneName = "";

        for (SafeZoneData zone : safeZonesList) {
            android.location.Location zoneLoc = new android.location.Location("zone");
            zoneLoc.setLatitude(zone.latitude);
            zoneLoc.setLongitude(zone.longitude);

            float distance = childLocation.distanceTo(zoneLoc);
            if (distance <= zone.radius) {
                insideAnyZone = true;
                insideZoneName = zone.name;
                break;
            }
        }

        if (insideAnyZone) {
            atualizarStatusZona(true, "Seguro em: " + insideZoneName);
        } else {
            atualizarStatusZona(false, "Longe das zonas seguras");
        }
    }

    // --- FUNÇÃO PARA MUDAR AS CORES DA ZONA (VERDE/LARANJA) ---
    private void atualizarStatusZona(boolean naZonaSegura, String subtitulo) {
        if (cardZoneStatus == null) return;

        if (naZonaSegura) {
            // MODO VERDE: Dentro de Zona Segura
            cardZoneStatus.setCardBackgroundColor(Color.parseColor("#9DCA43"));
            cardZoneIconBG.setCardBackgroundColor(Color.parseColor("#EAF4D4"));
            iconZone.setColorFilter(Color.parseColor("#5F8B1A"));

            txtZoneTitle.setText("Dentro de Zona Segura");
            txtZoneTitle.setTextColor(Color.parseColor("#2D4608"));
            txtZoneSubtitle.setText(subtitulo);
            txtZoneSubtitle.setTextColor(Color.parseColor("#486B11"));
        } else {
            // MODO LARANJA: Em Movimento / Fora de Zonas
            cardZoneStatus.setCardBackgroundColor(Color.parseColor("#FFA726"));
            cardZoneIconBG.setCardBackgroundColor(Color.parseColor("#FFE0B2"));
            iconZone.setColorFilter(Color.parseColor("#E65100"));

            txtZoneTitle.setText("A movimentar-se");
            txtZoneTitle.setTextColor(Color.parseColor("#822B00"));
            txtZoneSubtitle.setText(subtitulo);
            txtZoneSubtitle.setTextColor(Color.parseColor("#A63A00"));
        }
    }

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

    private void showEmptyState() {
        if (layoutEmptyState != null) layoutEmptyState.setVisibility(View.VISIBLE);
        if (mapContainer != null) mapContainer.setVisibility(View.GONE);
    }

    private void openAddChildScreen() {
        AddChildBottomSheet bottomSheet = new AddChildBottomSheet();
        bottomSheet.setListener(this::showCodeDialog);
        bottomSheet.show(getParentFragmentManager(), "AddChildSheet");
    }

    private void showCodeDialog(String code) {
        new AlertDialog.Builder(requireContext())
                .setTitle("Filho Adicionado!")
                .setMessage("Código: " + code)
                .setPositiveButton("OK", (d, w) -> checkIfHasChildren())
                .show();
    }

    private void centerOnChildLocation() {
        FirebaseUser user = auth.getCurrentUser();
        if (user != null && user.isAnonymous()) {
            if (androidx.core.content.ContextCompat.checkSelfPermission(requireContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == android.content.pm.PackageManager.PERMISSION_GRANTED) {
                com.google.android.gms.location.FusedLocationProviderClient fusedLocationClient = com.google.android.gms.location.LocationServices.getFusedLocationProviderClient(requireActivity());
                fusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
                    if (location != null && mMap != null) {
                        mMap.animateCamera(com.google.android.gms.maps.CameraUpdateFactory.newLatLngZoom(
                                new com.google.android.gms.maps.model.LatLng(location.getLatitude(), location.getLongitude()), 16f));
                    } else {
                        Toast.makeText(getContext(), "A procurar localização atual...", Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                Toast.makeText(getContext(), "Sem permissão de localização.", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        if (mMap != null && lastChildLocation != null) {
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lastChildLocation, 16f));
        } else {
            Toast.makeText(getContext(), "A aguardar localização do filho...", Toast.LENGTH_SHORT).show();
        }
    }
}