package com.example.vdcscore.ui.topscorers;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.vdcscore.R;
import com.example.vdcscore.models.TopScorer;
import com.google.android.material.button.MaterialButtonToggleGroup;
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 java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TopScorersFragment extends Fragment {

    private RecyclerView recyclerTopScorers;
    private TopScorersAdapter adapter;
    private MaterialButtonToggleGroup toggleGroupCategory;
    private TextView textEmptyState;
    
    private DatabaseReference mDatabase;
    private String currentCategory = "seniores";
    private ValueEventListener currentListener;

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

        View root = inflater.inflate(R.layout.fragment_top_scorers, container, false);

        recyclerTopScorers = root.findViewById(R.id.recycler_top_scorers);
        toggleGroupCategory = root.findViewById(R.id.toggleGroupCategory);
        textEmptyState = root.findViewById(R.id.text_empty_state);

        adapter = new TopScorersAdapter();
        recyclerTopScorers.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerTopScorers.setAdapter(adapter);

        toggleGroupCategory.addOnButtonCheckedListener((group, checkedId, isChecked) -> {
            if (isChecked) {
                if (checkedId == R.id.btn_seniores) {
                    currentCategory = "seniores";
                } else if (checkedId == R.id.btn_juniores) {
                    currentCategory = "juniores";
                }
                fetchTopScorers();
            }
        });

        fetchTopScorers();

        return root;
    }

    private void fetchTopScorers() {
        if (mDatabase != null && currentListener != null) {
            mDatabase.removeEventListener(currentListener);
        }

        textEmptyState.setVisibility(View.VISIBLE);
        textEmptyState.setText("A carregar dados...");
        recyclerTopScorers.setVisibility(View.GONE);

        mDatabase = FirebaseDatabase.getInstance().getReference("marcadores").child(currentCategory);

        currentListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (getContext() == null) return;
                
                List<TopScorer> scorersList = new ArrayList<>();
                for (DataSnapshot data : snapshot.getChildren()) {
                    TopScorer scorer = data.getValue(TopScorer.class);
                    if (scorer != null) {
                        scorersList.add(scorer);
                    }
                }

                // Ordenar por golos descrescente
                Collections.sort(scorersList, new Comparator<TopScorer>() {
                    @Override
                    public int compare(TopScorer s1, TopScorer s2) {
                        return Integer.compare(s2.getGoals(), s1.getGoals());
                    }
                });

                if (scorersList.isEmpty()) {
                    textEmptyState.setText("Ainda não existem marcadores registados.");
                    textEmptyState.setVisibility(View.VISIBLE);
                    recyclerTopScorers.setVisibility(View.GONE);
                } else {
                    textEmptyState.setVisibility(View.GONE);
                    recyclerTopScorers.setVisibility(View.VISIBLE);
                    
                    // Limitar aos top 10 marcadores
                    List<TopScorer> top10List = scorersList.subList(0, Math.min(10, scorersList.size()));
                    adapter.setTopScorers(top10List);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                if (getContext() != null) {
                    Toast.makeText(getContext(), "Erro ao carregar: " + error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        };

        mDatabase.addValueEventListener(currentListener);
    }

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