package com.example.vdcscore.ui.cup;

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

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.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.HashMap;
import java.util.List;
import java.util.Map;

public class CupFragment extends Fragment {

    private FragmentCupBinding binding;
    private CupPhasesAdapter adapter;
    private DatabaseReference mDatabase;
    private List<CupPhase> phasesList = new ArrayList<>();
    private String currentCategory = "seniores";
    private ValueEventListener currentListener;

    // Estrutura fixa das fases da Taça
    private static final String[] CUP_PHASES_ORDER = {
        "1ª Eliminatoria 1º Mão",
        "2ª Eliminatoria 2º Mão",
        "Quartos 1º Mão",
        "Quartos 2º Mão",
        "Meia Final 1º Mão",
        "Meia Final 2º Mão",
        "Final"
    };

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

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

        // Initialize RecyclerView
        adapter = new CupPhasesAdapter();
        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();
            }
        });

        // 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;

                // Obter todas as fases do Firebase
                List<String> allPhases = new ArrayList<>();
                for (DataSnapshot phaseSnap : snapshot.getChildren()) {
                    String name = phaseSnap.getKey();
                    if (name != null) {
                        allPhases.add(name);
                    }
                }

                if (allPhases.isEmpty()) {
                    binding.textPhaseName.setText("Sem fases");
                    adapter.setPhases(new ArrayList<>());
                    return;
                }

                // Tentar ordenar pela ordem fixa
                phasesList.clear();
                
                // Adicionar fases que estão na lista fixa (na ordem correta)
                for (String fixedPhase : CUP_PHASES_ORDER) {
                    for (String firebasePhase : allPhases) {
                        if (firebasePhase.equals(fixedPhase)) {
                            List<Match> matches = getMatchesFromSnapshot(snapshot, firebasePhase);
                            if (!matches.isEmpty()) {
                                phasesList.add(new CupPhase(fixedPhase, matches));
                            }
                            break;
                        }
                    }
                }

                // Adicionar fases que não estão na lista fixa (ordenadas alfabeticamente)
                List<String> remainingPhases = new ArrayList<>();
                for (String firebasePhase : allPhases) {
                    boolean isFixedPhase = false;
                    for (String fixed : CUP_PHASES_ORDER) {
                        if (fixed.equals(firebasePhase)) {
                            isFixedPhase = true;
                            break;
                        }
                    }
                    if (!isFixedPhase) {
                        remainingPhases.add(firebasePhase);
                    }
                }
                Collections.sort(remainingPhases);
                for (String remainingPhase : remainingPhases) {
                    List<Match> matches = getMatchesFromSnapshot(snapshot, remainingPhase);
                    if (!matches.isEmpty()) {
                        phasesList.add(new CupPhase(remainingPhase, matches));
                    }
                }

                if (phasesList.isEmpty()) {
                    binding.textPhaseName.setText("Sem fases");
                    adapter.setPhases(new ArrayList<>());
                } else {
                    binding.textPhaseName.setText(phasesList.get(0).getName());
                    adapter.setPhases(phasesList);
                }
            }

            private List<Match> getMatchesFromSnapshot(DataSnapshot snapshot, String phaseName) {
                List<Match> matches = new ArrayList<>();
                for (DataSnapshot phaseSnap : snapshot.getChildren()) {
                    if (phaseSnap.getKey() != null && phaseSnap.getKey().equals(phaseName)) {
                        for (DataSnapshot matchSnap : phaseSnap.getChildren()) {
                            Match match = matchSnap.getValue(Match.class);
                            if (match != null) {
                                match.setId(matchSnap.getKey());
                                matches.add(match);
                            }
                        }
                        break;
                    }
                }
                return matches;
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                if (getContext() != null) {
                    com.google.android.material.snackbar.Snackbar.make(binding.getRoot(), "Erro ao carregar taça: " + error.getMessage(), com.google.android.material.snackbar.Snackbar.LENGTH_SHORT).show();
                }
            }
        };

        mDatabase.addValueEventListener(currentListener);
    }

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