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.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.SupportMapFragment;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;

public class MapFragment extends Fragment {

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

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

        // Agora o Java vai encontrar estes IDs porque colocamos no XML acima
        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(); // Agora esta função existe lá embaixo
                } 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()) {
                        QuerySnapshot snapshot = task.getResult();
                        if (snapshot != null && !snapshot.isEmpty()) {
                            showMapState();
                        } else {
                            showEmptyState();
                        }
                    } else {
                        showEmptyState();
                    }
                });
    }

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

        Fragment existingMap = getChildFragmentManager().findFragmentById(R.id.mapContainer);
        if (existingMap == null) {
            SupportMapFragment googleMapFragment = SupportMapFragment.newInstance();
            getChildFragmentManager().beginTransaction()
                    .replace(R.id.mapContainer, googleMapFragment)
                    .commit();
        }
    }

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

    // Esta é a função que estava faltando ou mal fechada
    private void openAddChildScreen() {
        AddChildBottomSheet bottomSheet = new AddChildBottomSheet();

        bottomSheet.setListener(code -> {
            showCodeDialog(code);
        });

        bottomSheet.show(getParentFragmentManager(), "AddChildSheet");
    }

    private void showCodeDialog(String code) {
        if (getContext() == null) return;
        new AlertDialog.Builder(getContext())
                .setTitle("Perfil Criado!")
                .setMessage("Digite este código no telemóvel do filho:\n\n" + code)
                .setPositiveButton("Copiar Código", (dialog, which) -> {
                    ClipboardManager clipboard = (ClipboardManager) requireContext().getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("Código", code);
                    clipboard.setPrimaryClip(clip);
                    Toast.makeText(getContext(), "Copiado!", Toast.LENGTH_SHORT).show();
                })
                .show();
    }
}