package com.example.boidelov3.games.papelito;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.boidelov3.R;
import com.example.boidelov3.hub.GameSelectionActivity;

import java.util.ArrayList;
import java.util.Locale;

/**
 * Activité de fin de partie Papelito
 * Affiche les résultats, révèle tous les rôles et permet de rejouer
 */
public class PapelitoResultActivity extends AppCompatActivity {

    public static final String EXTRA_PLAYERS = "extra_players";
    public static final String EXTRA_WINNING_TEAM = "extra_winning_team";
    public static final String EXTRA_CIVIL_WORD = "extra_civil_word";
    public static final String EXTRA_UNDERCOVER_WORD = "extra_undercover_word";
    public static final String EXTRA_TOTAL_ROUNDS = "extra_total_rounds";

    private ArrayList<PapelitoPlayer> players;
    private PapelitoPlayer.Role winningTeam;
    private String civilWord;
    private String undercoverWord;
    private int totalRounds;

    private TextView textViewWinner;
    private TextView textViewWords;
    private TextView textViewRounds;
    private RecyclerView recyclerViewResults;
    private Button buttonNewGame;
    private Button buttonHome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_papelito_result);

        // Récupérer les données (compatibilité API 33+)
        ArrayList<PapelitoPlayer> players;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            players = getIntent().getSerializableExtra(EXTRA_PLAYERS, ArrayList.class);
        } else {
            players = (ArrayList<PapelitoPlayer>) getIntent().getSerializableExtra(EXTRA_PLAYERS);
        }
        this.players = players;

        PapelitoPlayer.Role winningTeam;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            winningTeam = getIntent().getSerializableExtra(EXTRA_WINNING_TEAM, PapelitoPlayer.Role.class);
        } else {
            winningTeam = (PapelitoPlayer.Role) getIntent().getSerializableExtra(EXTRA_WINNING_TEAM);
        }
        this.winningTeam = winningTeam;
        civilWord = getIntent().getStringExtra(EXTRA_CIVIL_WORD);
        undercoverWord = getIntent().getStringExtra(EXTRA_UNDERCOVER_WORD);
        totalRounds = getIntent().getIntExtra(EXTRA_TOTAL_ROUNDS, 0);

        // Add validation
        if (players == null || players.isEmpty()) {
            finish();
            return;
        }

        // Initialiser les vues
        initViews();

        // Afficher les résultats
        displayResults();
    }

    private void initViews() {
        textViewWinner = findViewById(R.id.winnerTextView);
        textViewWords = findViewById(R.id.undercoverWordTextView);
        textViewRounds = findViewById(R.id.roundsTextView);
        recyclerViewResults = findViewById(R.id.rolesRecyclerView);
        buttonNewGame = findViewById(R.id.newGameButton);
        buttonHome = findViewById(R.id.homeButton);

        // Configurer le RecyclerView
        recyclerViewResults.setLayoutManager(new LinearLayoutManager(this));
        
        // Bouton Nouvelle Partie
        buttonNewGame.setOnClickListener(v -> {
            Intent intent = new Intent(this, PapelitoSetupActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });

        // Bouton Retour Hub
        buttonHome.setOnClickListener(v -> {
            Intent intent = new Intent(this, GameSelectionActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        });
    }

    private void displayResults() {
        // Afficher l'équipe gagnante
        if (winningTeam != null) {
            String winnerText;
            int backgroundColor;
            
            if (winningTeam == PapelitoPlayer.Role.CIVIL) {
                winnerText = "🎉 LES CIVILS ONT GAGNÉ !";
                backgroundColor = getColor(R.color.civil_bg);
            } else {
                winnerText = "🔴 LES UNDERCOVERS ONT GAGNÉ !";
                backgroundColor = getColor(R.color.undercover_bg);
            }
            
            textViewWinner.setText(winnerText);
            findViewById(R.id.winnerCard).setBackgroundColor(backgroundColor);
        }

        // Afficher les mots (civilWordTextView et undercoverWordTextView)
        TextView civilWordView = findViewById(R.id.civilWordTextView);
        TextView undercoverWordView = findViewById(R.id.undercoverWordTextView);
        
        if (civilWordView != null) {
            civilWordView.setText("Mot Civil: " + (civilWord != null ? civilWord : "Non défini"));
        }
        if (undercoverWordView != null) {
            undercoverWordView.setText("Mot Undercover: " + (undercoverWord != null ? undercoverWord : "Non défini"));
        }

        // Afficher le nombre de tours
        String roundsText = "Nombre de manches: " + totalRounds;
        textViewRounds.setText(roundsText);

        // Configurer l'adaptateur pour afficher tous les joueurs
        PapelitoResultAdapter adapter = new PapelitoResultAdapter(players, civilWord, undercoverWord);
        recyclerViewResults.setAdapter(adapter);
    }
}
