package com.example.vdcscore.ui.clubs;

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

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

import com.example.vdcscore.R;
import com.example.vdcscore.databinding.FragmentClubsBinding;
import com.example.vdcscore.models.Club;
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.List;

public class ClubsFragment extends Fragment {

    private FragmentClubsBinding binding;
    private DatabaseReference mDatabase;
    private ValueEventListener mValueEventListener;
    private static final String TAG = "ClubsFragment";
    private String currentEscalao = "seniores"; // Default selection

    public View onCreateView(@NonNull LayoutInflater inflater,
            ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentClubsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        RecyclerView recyclerView = binding.recyclerClubs;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        ProgressBar progressBar = binding.progressBar;

        // 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";
                }
                loadClubsData(recyclerView, progressBar);
            }
        });

        // Initial Data Load
        loadClubsData(recyclerView, progressBar);

        return root;
    }

    private void loadClubsData(RecyclerView recyclerView, ProgressBar progressBar) {
        if (progressBar != null) progressBar.setVisibility(View.VISIBLE);

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

        mDatabase = FirebaseDatabase.getInstance().getReference().child("clubes");

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

                List<Club> clubs = new ArrayList<>();
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    if (postSnapshot.child("jogadores").child(currentEscalao).exists()) {
                        try {
                            Club club = postSnapshot.getValue(Club.class);
                            if (club != null) {
                                clubs.add(club);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                ClubAdapter adapter = new ClubAdapter(clubs, club -> {
                    if (binding == null) return;
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("clube_selecionado", club);
                    bundle.putString("escalao", currentEscalao);
                    androidx.navigation.fragment.NavHostFragment.findNavController(ClubsFragment.this)
                            .navigate(R.id.action_nav_clubs_to_nav_club_detail, bundle);
                });
                
                if (recyclerView != null) {
                    recyclerView.setAdapter(adapter);
                }
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Log.w(TAG, "loadClubs:onCancelled", error.toException());
                if (getContext() != null && binding != null) {
                    Toast.makeText(getContext(), "Failed to load clubs.", Toast.LENGTH_SHORT).show();
                    binding.progressBar.setVisibility(View.GONE);
                }
            }
        };

        mDatabase.addValueEventListener(mValueEventListener);
    }

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