package com.example.pap_findu.ui.map;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
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.Toast;

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

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.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
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.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;

public class MapFragment extends Fragment implements OnMapReadyCallback {

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

    // Variáveis para o Mapa e Tempo Real
    private GoogleMap mMap;
    private Marker childMarker;
    private DatabaseReference locationRef;
    private ValueEventListener locationListener;

    // VARIÁVEL ADICIONADA PARA GUARDAR O ID DA CRIANÇA AUTOMATICAMENTE
    private String currentChildId = null;

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

        if (btnAddChild != null) {
            btnAddChild.setOnClickListener(v -> {
                FirebaseUser user = auth.getCurrentUser();
                if (user != null) {
                    openAddChildScreen();
                } else {
                    Toast.makeText(getContext(), "Erro: Utilizador não autenticado", Toast.LENGTH_SHORT).show();
                }
            });
        }

        checkUserTypeAndShowScreen();

        return root;
    }

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

        if (user.isAnonymous()) {
            if (btnAddChild != null) btnAddChild.setVisibility(View.GONE);
            showMapState();
            return;
        }

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

                        // =================================================================
                        // AUTOMAÇÃO: Encontra a criança e extrai o ID dela!
                        // =================================================================
                        var document = task.getResult().getDocuments().get(0);

                        // MUITO IMPORTANTE: Mude "uid" para o nome do campo na sua base de dados que tem o ID do filho!
                        currentChildId = document.getString("uid");

                        if (currentChildId != null) {
                            showMapState(); // Se encontrou o ID, carrega o mapa
                        } else {
                            Toast.makeText(getContext(), "Erro: Criança encontrada, mas sem ID.", Toast.LENGTH_SHORT).show();
                            showEmptyState();
                        }
                    } else {
                        showEmptyState();
                    }
                });
    }

    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 = SupportMapFragment.newInstance();
            getChildFragmentManager().beginTransaction()
                    .replace(R.id.mapContainer, mapFragment)
                    .commit();
        }

        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(@NonNull GoogleMap googleMap) {
        mMap = googleMap;

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(0, 0), 2f));

        // Inicia a escuta APENAS se tivermos encontrado um ID válido
        if (currentChildId != null) {
            startListeningToChildLocation();
        } else {
            Toast.makeText(getContext(), "A aguardar ligação à criança...", Toast.LENGTH_SHORT).show();
        }
    }

    private void startListeningToChildLocation() {
        // =================================================================
        // AUTOMAÇÃO: Usa a variável currentChildId em vez de texto fixo
        // =================================================================
        locationRef = FirebaseDatabase.getInstance().getReference("users/" + currentChildId + "/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 && mMap != null) {
                        LatLng childPosition = new LatLng(lat, lng);

                        if (childMarker == null) {
                            MarkerOptions markerOptions = new MarkerOptions()
                                    .position(childPosition)
                                    .title("Criança");

                            childMarker = mMap.addMarker(markerOptions);
                            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(childPosition, 16f));
                        } else {
                            childMarker.setPosition(childPosition);
                            mMap.animateCamera(CameraUpdateFactory.newLatLng(childPosition));
                        }
                    }
                } else {
                    Log.w("MapFragment", "Pasta de localização vazia ou inexistente para o ID: " + currentChildId);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Log.e("MapFragment", "Erro ao ler localização: " + error.getMessage());
            }
        };

        locationRef.addValueEventListener(locationListener);
    }

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

    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) {
        if (getContext() == null) return;

        ClipboardManager clipboard = (ClipboardManager) requireContext().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("Código", code);
        clipboard.setPrimaryClip(clip);
        Toast.makeText(getContext(), "Código copiado!", Toast.LENGTH_SHORT).show();

        new AlertDialog.Builder(getContext())
                .setTitle("Filho Adicionado!")
                .setMessage("O código de acesso é: " + code + "\n\n(Já copiado automaticamente)")
                .setCancelable(false)
                .setPositiveButton("Ir para o Mapa", (dialog, which) -> checkIfHasChildren())
                .setNegativeButton("Adicionar Outro", (dialog, which) -> dialog.dismiss())
                .show();
    }
}