package com.example.vdcscore.ui.clubs;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.vdcscore.R;
import com.example.vdcscore.databinding.FragmentPlayerDetailBinding;
import com.example.vdcscore.models.Player;
import com.example.vdcscore.models.TopScorer;
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;

public class PlayerDetailFragment extends Fragment {

    private FragmentPlayerDetailBinding binding;

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

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

        if (getArguments() != null) {
            Player jogadorRecebido = (Player) getArguments().getSerializable("jogador_selecionado");

            if (jogadorRecebido != null) {
                binding.textDetailPlayerName.setText(jogadorRecebido.getNome());

                String birthDate = jogadorRecebido.getDataNascimento();
                binding.textDetailBirthdate.setText(birthDate != null && !birthDate.isEmpty() ? birthDate : "N/D");

                String birthplace = jogadorRecebido.getNaturalidade();
                binding.textDetailBirthplace.setText(birthplace != null && !birthplace.isEmpty() ? birthplace : "N/D");

                if (getContext() != null) {
                    Glide.with(this)
                            .load(jogadorRecebido.getFoto())
                            .placeholder(R.drawable.ic_menu_camera)
                            .error(R.drawable.ic_menu_camera)
                            .circleCrop()
                            .into(binding.imageDetailPlayerPhoto);
                }

                // Carregar golos da base de dados
                fetchPlayerGoals(jogadorRecebido.getNome());
            }
        }
    }

    private void fetchPlayerGoals(String playerName) {
        if (playerName == null || playerName.isEmpty()) {
            binding.textDetailTotalGoals.setText("0");
            return;
        }

        DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("marcadores");
        
        mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (binding == null) return;
                
                int totalGoals = 0;

                // Iterar sobre as subcategorias (seniores, juniores, etc)
                for (DataSnapshot categorySnapshot : snapshot.getChildren()) {
                    // Iterar sobre cada marcador individualmente
                    for (DataSnapshot data : categorySnapshot.getChildren()) {
                        TopScorer scorer = data.getValue(TopScorer.class);
                        if (scorer != null && scorer.getPlayerName() != null 
                                && scorer.getPlayerName().equalsIgnoreCase(playerName)) {
                            totalGoals += scorer.getGoals();
                        }
                    }
                }

                binding.textDetailTotalGoals.setText(String.valueOf(totalGoals));
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                if (binding != null) {
                    binding.textDetailTotalGoals.setText("Erro");
                }
            }
        });
    }

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