package com.example.pap_findu.ui.home;

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.firebase.Timestamp;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class HomeFragment extends Fragment {

    private Button btnAddChild;
    private FirebaseFirestore db;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        // 1. AQUI É O SEGREDO: Ele vai carregar o design do 'fragment_home.xml'
        // Se o seu arquivo XML com o design azul tiver outro nome, mude aqui.
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        // 2. Inicializar o Firebase e o Botão
        db = FirebaseFirestore.getInstance();
        btnAddChild = root.findViewById(R.id.btnAddChild);

        // 3. Ação do Botão
        if (btnAddChild != null) {
            btnAddChild.setOnClickListener(v -> {
                // Substitua pelo ID real do pai logado depois
                String parentId = "ID_DO_PAI_TESTE";
                generateCode(parentId);
            });
        }

        return root;
    }

    private void generateCode(String parentId) {
        String code = String.valueOf((int)(Math.random() * 900000) + 100000);
        Timestamp expiresAt = new Timestamp(new Date(System.currentTimeMillis() + 10 * 60 * 1000));

        Map<String, Object> codeMap = new HashMap<>();
        codeMap.put("parentId", parentId);
        codeMap.put("expiresAt", expiresAt);
        codeMap.put("used", false);

        db.collection("login_codes").document(code)
                .set(codeMap)
                .addOnSuccessListener(aVoid -> showCodeDialog(code))
                .addOnFailureListener(e -> Toast.makeText(getContext(), "Erro ao criar código", Toast.LENGTH_SHORT).show());
    }

    private void showCodeDialog(String code) {
        if (getContext() == null) return;

        new AlertDialog.Builder(getContext())
                .setTitle("Adicionar Novo Filho")
                .setMessage("Código de acesso: " + code)
                .setPositiveButton("Copiar", (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();
                })
                .setNegativeButton("Fechar", null)
                .show();
    }
}