package com.example.vdcscore.ui.home;

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

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

import com.example.vdcscore.R;
import com.example.vdcscore.databinding.FragmentHomeBinding;
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 HomeFragment extends Fragment {

    private FragmentHomeBinding binding;
    private StandingsAdapter adapter;
    private DatabaseReference mDatabase;
    private ValueEventListener mValueEventListener;
    private String currentEscalao = "seniores";

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

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // Initialize RecyclerView
        adapter = new StandingsAdapter();
        adapter.setOnTeamClickListener(team -> {
            Bundle bundle = new Bundle();
            bundle.putSerializable("clube_selecionado_estatisticas", team);
            bundle.putString("escalao", currentEscalao);
            androidx.navigation.Navigation.findNavController(root).navigate(R.id.action_nav_home_to_nav_club_detail, bundle);
        });
        binding.recyclerStandings.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerStandings.setAdapter(adapter);

        // Set up toggle listener
        binding.toggleGroupEscalao.addOnButtonCheckedListener((group, checkedId, isChecked) -> {
            if (isChecked) {
                if (checkedId == R.id.btnJuniores) {
                    currentEscalao = "juniores";
                } else if (checkedId == R.id.btnSeniores) {
                    currentEscalao = "seniores";
                }
                fetchStandings();
            }
        });

        // Fetch Data for default escalao
        fetchStandings();

        return root;
    }

    private void fetchStandings() {
        // Remove previous listener from the PREVIOUS path
        if (mDatabase != null && mValueEventListener != null) {
            mDatabase.removeEventListener(mValueEventListener);
        }

        mDatabase = FirebaseDatabase.getInstance().getReference("classificacoes").child(currentEscalao);

        mValueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (binding == null) return;

                List<Team> teams = new ArrayList<>();
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    try {
                        Team team = postSnapshot.getValue(Team.class);
                        if (team != null) {
                            if (team.getTeam_id() == 0) {
                                try {
                                    team.setTeam_id(Integer.parseInt(postSnapshot.getKey()));
                                } catch (NumberFormatException e) {
                                    // fallback if key is not a number
                                }
                            }
                            teams.add(team);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                // Set positions after sorting
                for (int i = 0; i < teams.size(); i++) {
                    teams.get(i).setPosicao(i + 1);
                }

                if (adapter != null) {
                    adapter.setTeams(teams);
                }
            }

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

        mDatabase.addValueEventListener(mValueEventListener);
    }

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