package com.example.vdcscore.ui.gallery;

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.FragmentGalleryBinding;
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 GalleryFragment extends Fragment {

    private FragmentGalleryBinding binding;
    private MatchesAdapter adapter;
    private DatabaseReference mDatabase;
    private List<Matchday> matchdaysList = new ArrayList<>();
    private int currentJornadaIndex = 0;
    private String currentCategory = "seniores";
    private ValueEventListener currentListener;

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

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

        // Initialize RecyclerView
        adapter = new MatchesAdapter();
        binding.recyclerMatchdays.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerMatchdays.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";
                }
                fetchMatchdays();
            }
        });

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

        binding.btnNextJornada.setOnClickListener(v -> {
            if (currentJornadaIndex < matchdaysList.size() - 1) {
                currentJornadaIndex++;
                updateUI();
            }
        });

        // Initial Fetch
        fetchMatchdays();

        return root;
    }

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

        binding.textJornadaName.setText("Carregando...");
        mDatabase = FirebaseDatabase.getInstance().getReference("jornadas").child(currentCategory);

        currentListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (binding == null) return;
                
                matchdaysList.clear();
                for (DataSnapshot jornadaSnap : snapshot.getChildren()) {
                    String name = jornadaSnap.getKey();
                    List<Match> matches = new ArrayList<>();
                    
                    for (DataSnapshot matchSnap : jornadaSnap.getChildren()) {
                        Match match = matchSnap.getValue(Match.class);
                        if (match != null) {
                            match.setId(matchSnap.getKey());
                            matches.add(match);
                        }
                    }
                    
                    if (!matches.isEmpty()) {
                        matchdaysList.add(new Matchday(name, matches));
                    }
                }

                // Sort matchdays numerically (e.g. "1" before "10")
                Collections.sort(matchdaysList, new Comparator<Matchday>() {
                    @Override
                    public int compare(Matchday m1, Matchday m2) {
                        try {
                            Integer num1 = Integer.parseInt(m1.getName());
                            Integer num2 = Integer.parseInt(m2.getName());
                            return num1.compareTo(num2);
                        } catch (NumberFormatException e) {
                            return m1.getName().compareTo(m2.getName());
                        }
                    }
                });

                if (matchdaysList.isEmpty()) {
                    binding.textJornadaName.setText("Sem jornadas");
                    adapter.setMatches(new ArrayList<>());
                } else {
                    // Try to stay on the same index or go to the first one
                    if (currentJornadaIndex >= matchdaysList.size()) {
                        currentJornadaIndex = matchdaysList.size() - 1;
                    }
                    updateUI();
                }
            }

            @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);
    }

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

        Matchday currentMatchday = matchdaysList.get(currentJornadaIndex);
        binding.textJornadaName.setText(formatJornadaName(currentMatchday.getName()));
        adapter.setMatches(currentMatchday.getMatches());

        // Enable/Disable navigation buttons
        binding.btnPrevJornada.setEnabled(currentJornadaIndex > 0);
        binding.btnNextJornada.setEnabled(currentJornadaIndex < matchdaysList.size() - 1);
        
        // Visual feedback for disabled buttons
        binding.btnPrevJornada.setAlpha(currentJornadaIndex > 0 ? 1.0f : 0.3f);
        binding.btnNextJornada.setAlpha(currentJornadaIndex < matchdaysList.size() - 1 ? 1.0f : 0.3f);
    }

    private String formatJornadaName(String name) {
        if (name == null) return "---";
        // If the name is just a number, format it as "Xª Jornada"
        try {
            int num = Integer.parseInt(name);
            return num + "ª Jornada";
        } catch (NumberFormatException e) {
            // If it's already a full name like "Jornada 1", return as is
            return name;
        }
    }

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