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.navigation.Navigation;

import com.example.vdcscore.R;
import com.example.vdcscore.databinding.FragmentClubDetailBinding;
import com.example.vdcscore.models.Club;
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 com.example.vdcscore.ui.home.Team;
import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.TextView;

public class ClubDetailFragment extends Fragment {

    private FragmentClubDetailBinding 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 = FragmentClubDetailBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

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

        if (getArguments() != null) {
            Team statsTeam = (Team) getArguments().getSerializable("clube_selecionado_estatisticas");

            if (statsTeam != null) {
                populateStats(statsTeam);
                setupComparison(statsTeam);
                // Also load basic info metadata (president, etc.)
                loadClubDetails(statsTeam.getTeam_id());
            } else {
                Club clubeRecebido = (Club) getArguments().getSerializable("clube_selecionado");
                if (clubeRecebido != null) {
                    populateClubInfo(clubeRecebido);
                } else if (clubId != null) {
                    loadClubDetails(Integer.parseInt(clubId));
                }
            }
        }
    }

    private void loadClubDetails(int clubId) {
        DatabaseReference clubRef = FirebaseDatabase.getInstance().getReference("clubes").child(String.valueOf(clubId));
        clubRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                Club club = snapshot.getValue(Club.class);
                if (club != null) {
                    populateClubInfo(club);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                if (getContext() != null) {
                    Toast.makeText(getContext(), "Erro ao carregar detalhes do clube", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void populateStats(Team team) {
        binding.textDetailClubName.setText(team.getNome());
        binding.labelStats.setVisibility(View.VISIBLE);
        binding.containerStats.setVisibility(View.VISIBLE);
        binding.btnCompare.setVisibility(View.VISIBLE);

        binding.textDetailPoints.setText(String.valueOf(team.getPontos()));
        binding.textDetailPlayed.setText(String.valueOf(team.getJogos()));
        binding.textDetailWon.setText(team.getVitorias() + "V");
        binding.textDetailDrawn.setText(team.getEmpates() + "E");
        binding.textDetailLost.setText(team.getDerrotas() + "D");
        binding.textDetailGoals.setText(team.getGolos_marcados() + " - " + team.getGolos_sofridos());
        binding.textDetailGoalDiff.setText((team.getDiferenca_golos() > 0 ? "+" : "") + team.getDiferenca_golos());
        
        // Posicao circle and text
        binding.textDetailPosition.setText(team.getPosicao() > 0 ? team.getPosicao() + "º" : "---");
        binding.textDetailPositionCircle.setText(String.valueOf(team.getPosicao() > 0 ? team.getPosicao() : "-"));

        if (getContext() != null) {
            Glide.with(this)
                    .load(team.getImagem())
                    .placeholder(R.mipmap.ic_launcher_round)
                    .error(R.mipmap.ic_launcher)
                    .into(binding.imageDetailLogo);
        }

        // Button players
        binding.btnPlayers.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("clubId", String.valueOf(team.getTeam_id()));
            bundle.putString("escalao", escalao);
            Navigation.findNavController(v).navigate(R.id.action_nav_club_detail_to_nav_club_players, bundle);
        });
    }

    private void populateClubInfo(Club club) {
        binding.textDetailClubName.setText(club.getName());
        
        // Bind new club info fields
        binding.textDetailPresident.setText(club.getPresident() != null && !club.getPresident().isEmpty() ? club.getPresident() : "---");
        binding.textDetailFoundation.setText(club.getFoundationYear() > 0 ? String.valueOf(club.getFoundationYear()) : "---");
        binding.textDetailStadium.setText(club.getStadium() != null && !club.getStadium().isEmpty() ? club.getStadium() : "---");
        binding.textDetailAddress.setText(club.getAddress() != null && !club.getAddress().isEmpty() ? club.getAddress() : "---");

        if (getContext() != null) {
            Glide.with(this)
                    .load(club.getImageUrl())
                    .placeholder(R.mipmap.ic_launcher_round)
                    .error(R.mipmap.ic_launcher)
                    .into(binding.imageDetailLogo);
        }
        
        binding.btnPlayers.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString("clubId", String.valueOf(club.getId()));
            bundle.putString("escalao", escalao);
            Navigation.findNavController(v).navigate(R.id.action_nav_club_detail_to_nav_club_players, bundle);
        });

        // Tenta carregar estatísticas em segundo plano baseando-se no nome do clube
        searchAndLinkTeamStats(club.getName());
    }

    private void searchAndLinkTeamStats(String clubName) {
        if (clubName == null) return;

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference("classificacoes");
        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (binding == null) return;

                // Iterar sobre todos os escalões disponíveis
                for (DataSnapshot escalaoSnapshot : snapshot.getChildren()) {
                    // Iterar sobre as equipas dentro de cada escalão
                    for (DataSnapshot teamSnapshot : escalaoSnapshot.getChildren()) {
                        Team candidate = teamSnapshot.getValue(Team.class);
                        if (candidate != null && candidate.getNome() != null 
                                && candidate.getNome().equalsIgnoreCase(clubName)) {
                            // Sucesso! Encontrámos as estatísticas.
                            // Guardar escalao caso não estivesse definido
                            if (escalao == null) {
                                escalao = escalaoSnapshot.getKey();
                            }
                            populateStats(candidate);
                            setupComparison(candidate);
                            return; // Parar de procurar
                        }
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {}
        });
    }

    private void setupComparison(Team team1) {
        binding.btnCompare.setOnClickListener(v -> {
            // Fetch all teams of same escalao if not fetched
            FirebaseDatabase.getInstance().getReference("classificacoes").child(escalao)
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        java.util.List<Team> otherTeams = new java.util.ArrayList<>();
                        for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                            Team t = postSnapshot.getValue(Team.class);
                            if (t != null && t.getTeam_id() != team1.getTeam_id()) {
                                otherTeams.add(t);
                            }
                        }
                        showComparisonDialog(team1, otherTeams);
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {}
                });
        });
    }

    private void showComparisonDialog(Team team1, java.util.List<Team> otherTeams) {
        if (getContext() == null) return;

        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(requireContext());
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_team_selector, null);
        bottomSheetDialog.setContentView(dialogView);

        RecyclerView recyclerView = dialogView.findViewById(R.id.recycler_comparison_teams);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        
        // Configurar um adapter simples e direto
        recyclerView.setAdapter(new RecyclerView.Adapter<CompareViewHolder>() {
            @NonNull
            @Override
            public CompareViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comparison_selector, parent, false);
                return new CompareViewHolder(v);
            }

            @Override
            public void onBindViewHolder(@NonNull CompareViewHolder holder, int position) {
                Team currentTeam = otherTeams.get(position);
                holder.nameText.setText(currentTeam.getNome());
                holder.posText.setText(currentTeam.getPosicao() > 0 ? currentTeam.getPosicao() + "º" : "-");
                
                Glide.with(holder.itemView.getContext())
                        .load(currentTeam.getImagem())
                        .placeholder(R.mipmap.ic_launcher_round)
                        .into(holder.logoImage);

                holder.itemView.setOnClickListener(v -> {
                    bottomSheetDialog.dismiss();
                    displayComparison(team1, currentTeam);
                });
            }

            @Override
            public int getItemCount() {
                return otherTeams.size();
            }
        });

        bottomSheetDialog.show();
    }

    // ViewHolder auxiliar para o recycler local
    private static class CompareViewHolder extends RecyclerView.ViewHolder {
        ImageView logoImage;
        TextView nameText, posText;

        public CompareViewHolder(@NonNull View itemView) {
            super(itemView);
            logoImage = itemView.findViewById(R.id.img_team_logo);
            nameText = itemView.findViewById(R.id.text_team_name);
            posText = itemView.findViewById(R.id.text_team_position);
        }
    }

    private void displayComparison(Team t1, Team t2) {
        // IMPORTANTE: Ativar a CARD (contentor) e não apenas o layout interno!
        binding.cardComparison.setVisibility(View.VISIBLE);
        
        // Set Names
        binding.textCompareTeam1.setText(t1.getNome());
        binding.textCompareTeam2.setText(t2.getNome());

        // Load comparison logos dynamically
        if (getContext() != null) {
            Glide.with(this).load(t1.getImagem()).placeholder(R.mipmap.ic_launcher_round).into(binding.imgCompareTeam1);
            Glide.with(this).load(t2.getImagem()).placeholder(R.mipmap.ic_launcher_round).into(binding.imgCompareTeam2);
        }
        
        // Bind values
        binding.textCompareP1.setText(String.valueOf(t1.getPontos()));
        binding.textCompareP2.setText(String.valueOf(t2.getPontos()));
        
        binding.textCompareG1.setText(String.valueOf(t1.getGolos_marcados()));
        binding.textCompareG2.setText(String.valueOf(t2.getGolos_marcados()));

        // Supporting extra items to make it richer
        binding.textCompareJ1.setText(String.valueOf(t1.getJogos()));
        binding.textCompareJ2.setText(String.valueOf(t2.getJogos()));

        binding.textCompareV1.setText(String.valueOf(t1.getVitorias()));
        binding.textCompareV2.setText(String.valueOf(t2.getVitorias()));
        
        // Resourcing dynamic colors
        int successColor = getResources().getColor(R.color.brand);
        int defaultColor = getResources().getColor(R.color.text_3);

        // Applying visual highlights conditionally based on performance metrics
        
        // 1. Compare Pontos
        binding.textCompareP1.setTextColor(t1.getPontos() > t2.getPontos() ? successColor : defaultColor);
        binding.textCompareP1.setTypeface(null, t1.getPontos() > t2.getPontos() ? android.graphics.Typeface.BOLD : android.graphics.Typeface.NORMAL);
        binding.textCompareP2.setTextColor(t2.getPontos() > t1.getPontos() ? successColor : defaultColor);
        binding.textCompareP2.setTypeface(null, t2.getPontos() > t1.getPontos() ? android.graphics.Typeface.BOLD : android.graphics.Typeface.NORMAL);

        // 2. Compare Vitorias
        binding.textCompareV1.setTextColor(t1.getVitorias() > t2.getVitorias() ? successColor : defaultColor);
        binding.textCompareV1.setTypeface(null, t1.getVitorias() > t2.getVitorias() ? android.graphics.Typeface.BOLD : android.graphics.Typeface.NORMAL);
        binding.textCompareV2.setTextColor(t2.getVitorias() > t1.getVitorias() ? successColor : defaultColor);
        binding.textCompareV2.setTypeface(null, t2.getVitorias() > t1.getVitorias() ? android.graphics.Typeface.BOLD : android.graphics.Typeface.NORMAL);

        // 3. Compare Golos
        binding.textCompareG1.setTextColor(t1.getGolos_marcados() > t2.getGolos_marcados() ? successColor : defaultColor);
        binding.textCompareG1.setTypeface(null, t1.getGolos_marcados() > t2.getGolos_marcados() ? android.graphics.Typeface.BOLD : android.graphics.Typeface.NORMAL);
        binding.textCompareG2.setTextColor(t2.getGolos_marcados() > t1.getGolos_marcados() ? successColor : defaultColor);
        binding.textCompareG2.setTypeface(null, t2.getGolos_marcados() > t1.getGolos_marcados() ? android.graphics.Typeface.BOLD : android.graphics.Typeface.NORMAL);
    }

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