package com.example.vdcscore.ui.clubs;

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.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.vdcscore.databinding.FragmentClubPlayersBinding;
import com.example.vdcscore.models.Club;
import com.example.vdcscore.models.Player;
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 ClubPlayersFragment extends Fragment {

    private FragmentClubPlayersBinding binding;
    private DatabaseReference mDatabase;
    private String clubId;
    private String escalao;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            clubId = getArguments().getString("clubId");
            escalao = getArguments().getString("escalao");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        binding = FragmentClubPlayersBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        binding.recyclerPlayersList.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.progressBarPlayers.setVisibility(View.VISIBLE);

        if (clubId != null && escalao != null) {
            mDatabase = FirebaseDatabase.getInstance().getReference().child("clubes").child(clubId).child("jogadores")
                    .child(escalao);
            loadPlayers();
        } else {
            binding.progressBarPlayers.setVisibility(View.GONE);
            binding.textNoPlayers.setVisibility(View.VISIBLE);
            binding.textNoPlayers.setText("Erro: Clube ou escalão não identificado.");
        }
    }

    private void loadPlayers() {
        mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                binding.progressBarPlayers.setVisibility(View.GONE);

                List<Player> playerList = new ArrayList<>();
                if (snapshot.exists()) {
                    for (DataSnapshot playerSnapshot : snapshot.getChildren()) {
                        Player player = playerSnapshot.getValue(Player.class);
                        if (player != null) {
                            playerList.add(player);
                        }
                    }
                }

                if (!playerList.isEmpty()) {
                    PlayerAdapter adapter = new PlayerAdapter(playerList, player -> {
                        android.os.Bundle bundle = new android.os.Bundle();
                        bundle.putSerializable("jogador_selecionado", player);
                        androidx.navigation.Navigation.findNavController(requireView()).navigate(
                                com.example.vdcscore.R.id.action_nav_club_players_to_nav_player_detail, bundle);
                    });
                    binding.recyclerPlayersList.setAdapter(adapter);
                    binding.textNoPlayers.setVisibility(View.GONE);
                } else {
                    binding.textNoPlayers.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                if (getContext() != null) {
                    Toast.makeText(getContext(), "Failed to load players.", Toast.LENGTH_SHORT).show();
                }
                binding.progressBarPlayers.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
