package com.example.pap_findu.ui.map;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
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 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...";

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

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

    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;
        FirebaseUser user = auth.getCurrentUser();

        if (user != null && user.isAnonymous()) {
            try { mMap.setMyLocationEnabled(true); } catch (SecurityException e) {}
        } 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) {
                        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));

                            // TESTE DE DESIGN
                            atualizarStatusZona(true, "A atualizar localização...");
                        }
                    }
                }
            }
            @Override public void onCancelled(@NonNull DatabaseError error) {}
        };
        locationRef.addValueEventListener(locationListener);
    }

    // --- 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("Fora das zonas seguras");
            txtZoneSubtitle.setTextColor(Color.parseColor("#A63A00"));
        }
    }

    @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) {
        new AlertDialog.Builder(requireContext())
                .setTitle("Filho Adicionado!")
                .setMessage("Código: " + code)
                .setPositiveButton("OK", (d, w) -> checkIfHasChildren())
                .show();
    }
}