package com.example.vdcscore.ui.cup;

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.FragmentCupBinding;
import com.example.vdcscore.ui.gallery.Match;
import com.example.vdcscore.ui.gallery.Matchday;
import com.example.vdcscore.ui.gallery.MatchesAdapter;
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.List;

public class CupFragment extends Fragment {

    private FragmentCupBinding binding;
    private MatchesAdapter adapter;
    private DatabaseReference mDatabase;
    private List<Matchday> phasesList = new ArrayList<>(); // Reusing Matchday as generalized 'Phase'
    private int currentPhaseIndex = 0;
    private String currentCategory = "seniores";
    private ValueEventListener currentListener;

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

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

        // Initialize RecyclerView with reused MatchesAdapter
        adapter = new MatchesAdapter();
        binding.recyclerPhases.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerPhases.setAdapter(adapter);

        // Setup Toggle Group
        binding.toggleGroupCategory.addOnButtonCheckedListener((group, checkedId, isChecked) -> {
            if (isChecked) {
                if (checkedId == R.id.btn_seniores) {
                    currentCategory = "seniores";
                } else if (checkedId == R.id.btn_juniores) {
                    currentCategory = "juniores";
                }
                fetchPhases();
            }
        });

        // Setup Navigation Buttons
        binding.btnPrevPhase.setOnClickListener(v -> {
            if (currentPhaseIndex > 0) {
                currentPhaseIndex--;
                updateUI();
            }
        });

        binding.btnNextPhase.setOnClickListener(v -> {
            if (currentPhaseIndex < phasesList.size() - 1) {
                currentPhaseIndex++;
                updateUI();
            }
        });

        // Initial Fetch
        fetchPhases();

        return root;
    }

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

        binding.textPhaseName.setText("Carregando...");
        mDatabase = FirebaseDatabase.getInstance().getReference("taça").child(currentCategory);

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

                phasesList.clear();
                for (DataSnapshot phaseSnap : snapshot.getChildren()) {
                    String name = phaseSnap.getKey();
                    List<Match> matches = new ArrayList<>();

                    for (DataSnapshot matchSnap : phaseSnap.getChildren()) {
                        Match match = matchSnap.getValue(Match.class);
                        if (match != null) {
                            match.setId(matchSnap.getKey());
                            matches.add(match);
                        }
                    }

                    if (!matches.isEmpty()) {
                        phasesList.add(new Matchday(name, matches));
                    }
                }

                // Sort alphabetically/chronologically as they are phrases like "1ª Fase", "Oitavos", etc.
                Collections.sort(phasesList, (p1, p2) -> p1.getName().compareTo(p2.getName()));

                if (phasesList.isEmpty()) {
                    binding.textPhaseName.setText("Sem fases");
                    adapter.setMatches(new ArrayList<>());
                } else {
                    if (currentPhaseIndex >= phasesList.size()) {
                        currentPhaseIndex = phasesList.size() - 1;
                    }
                    // In case initial load or filter swap, bound index.
                    if (currentPhaseIndex < 0) currentPhaseIndex = 0;
                    updateUI();
                }
            }

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

        mDatabase.addValueEventListener(currentListener);
    }

    private void updateUI() {
        if (phasesList.isEmpty()) return;

        Matchday currentPhase = phasesList.get(currentPhaseIndex);
        binding.textPhaseName.setText(currentPhase.getName());
        adapter.setMatches(currentPhase.getMatches());

        // Enable/Disable navigation buttons
        binding.btnPrevPhase.setEnabled(currentPhaseIndex > 0);
        binding.btnNextPhase.setEnabled(currentPhaseIndex < phasesList.size() - 1);

        // Visual feedback
        binding.btnPrevPhase.setAlpha(currentPhaseIndex > 0 ? 1.0f : 0.3f);
        binding.btnNextPhase.setAlpha(currentPhaseIndex < phasesList.size() - 1 ? 1.0f : 0.3f);
    }

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