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

        // Encontra os IDs no XML
        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()) {
                        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);
    }

    private void openAddChildScreen() {
        AddChildBottomSheet bottomSheet = new AddChildBottomSheet();

        bottomSheet.setListener(code -> {
            // Quando o código é gerado, mostramos o diálogo de escolha
            showCodeDialog(code);
        });

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

    // --- AQUI ESTÁ A MUDANÇA PRINCIPAL ---
    private void showCodeDialog(String code) {
        if (getContext() == null) return;

        // 1. Copia o código automaticamente para a área de transferência
        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();

        // 2. Cria o Alerta com as Duas Opções
        new AlertDialog.Builder(getContext())
                .setTitle("Filho Adicionado!")
                .setMessage("O código de acesso é: " + code + "\n\n(Já copiado automaticamente)")
                .setCancelable(false) // Impede fechar clicando fora

                // OPÇÃO 1: Ir para o Mapa (Atualiza a tela)
                .setPositiveButton("Ir para o Mapa", (dialog, which) -> {
                    checkIfHasChildren(); // <--- Esta função recarrega a tela e mostra o mapa
                })

                // OPÇÃO 2: Adicionar Outro (Fica na mesma tela)
                .setNegativeButton("Adicionar Outro", (dialog, which) -> {
                    dialog.dismiss(); // Apenas fecha o alerta e continua na tela azul
                })
                .show();
    }
}