package com.example.boidelov3.games.boideloclassic;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.boidelov3.R;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;

import java.util.ArrayList;
import java.util.List;

/**
 * BoideloClassicSetupActivity - Écran de configuration du jeu Boidelo Classic
 * Version simplifiée comme 89++
 */
public class BoideloClassicSetupActivity extends AppCompatActivity {
    
    private static final int MIN_PLAYERS = 3;
    private static final int MAX_PLAYERS = 15;
    
    private LinearLayout playersContainer;
    private MaterialButton addPlayerButton;
    private MaterialButton startGameButton;
    private TextView playerCountText;
    private MaterialToolbar toolbar;

    private final List<String> playerNames = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_boidelo_classic_setup);
        
        initViews();
        setupToolbar();
        setupListeners();
        
        // Ajouter 3 joueurs par défaut
        addPlayerRow();
        addPlayerRow();
        addPlayerRow();
        
        // Initialiser le compteur
        updatePlayerCountText();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        playersContainer = findViewById(R.id.playersContainer);
        addPlayerButton = findViewById(R.id.addPlayerButton);
        startGameButton = findViewById(R.id.startGameButton);
        playerCountText = findViewById(R.id.playerCountText);
    }
    
    private void setupToolbar() {
        toolbar.setNavigationOnClickListener(v -> finish());
    }
    
    private void setupListeners() {
        addPlayerButton.setOnClickListener(v -> {
            if (playersContainer.getChildCount() < MAX_PLAYERS) {
                addPlayerRow();
            } else {
                Toast.makeText(this, "Maximum " + MAX_PLAYERS + " joueurs", Toast.LENGTH_SHORT).show();
            }
        });

        startGameButton.setOnClickListener(v -> goToParams());
    }
    
    private void addPlayerRow() {
        View playerRow = LayoutInflater.from(this).inflate(R.layout.item_player_row, playersContainer, false);
        
        TextInputEditText playerNameEdit = playerRow.findViewById(R.id.playerName);
        MaterialButton removeButton = playerRow.findViewById(R.id.removePlayerButton);
        TextView playerNumber = playerRow.findViewById(R.id.playerNumber);
        
        int position = playersContainer.getChildCount();
        playerNumber.setText(String.valueOf(position + 1));
        
        // Cacher le bouton de suppression pour les 3 premiers joueurs (minimum requis)
        if (position < MIN_PLAYERS) {
            removeButton.setVisibility(View.GONE);
        }
        
        removeButton.setOnClickListener(v -> {
            if (playersContainer.getChildCount() > MIN_PLAYERS) {
                playersContainer.removeView(playerRow);
                updatePlayerNumbers();
                updatePlayerNames();
            } else {
                Toast.makeText(this, "Minimum " + MIN_PLAYERS + " joueurs", Toast.LENGTH_SHORT).show();
            }
        });
        
        playerNameEdit.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                updatePlayerNames();
            }
        });
        
        playersContainer.addView(playerRow);
        updatePlayerCountText();
        updateStartButton();
    }
    
    private void updatePlayerNumbers() {
        for (int i = 0; i < playersContainer.getChildCount(); i++) {
            View row = playersContainer.getChildAt(i);
            TextView playerNumber = row.findViewById(R.id.playerNumber);
            playerNumber.setText(String.valueOf(i + 1));
            
            // Afficher le bouton de suppression uniquement au-delà du minimum
            MaterialButton removeButton = row.findViewById(R.id.removePlayerButton);
            if (i >= MIN_PLAYERS) {
                removeButton.setVisibility(View.VISIBLE);
            } else {
                removeButton.setVisibility(View.GONE);
            }
        }
        updatePlayerCountText();
    }
    
    private void updatePlayerNames() {
        playerNames.clear();
        for (int i = 0; i < playersContainer.getChildCount(); i++) {
            View row = playersContainer.getChildAt(i);
            TextInputEditText edit = row.findViewById(R.id.playerName);
            String name = edit.getText().toString().trim();
            if (!TextUtils.isEmpty(name)) {
                playerNames.add(name);
            } else {
                playerNames.add("Joueur " + (i + 1));
            }
        }
        updateStartButton();
    }
    
    private void updatePlayerCountText() {
        int count = playersContainer.getChildCount();
        playerCountText.setText("Joueurs: " + count + " / min. " + MIN_PLAYERS);
    }
    
    private void updateStartButton() {
        int validPlayers = playersContainer.getChildCount();
        boolean canStart = validPlayers >= MIN_PLAYERS;
        startGameButton.setEnabled(canStart);
        startGameButton.setText(canStart ? "PARAMÈTRES ET JEU (" + validPlayers + ")" : "Ajoutez des joueurs");
    }
    
    /**
     * Redirige vers l'écran des paramètres avant de lancer le jeu
     */
    private void goToParams() {
        // Vérifier que tous les champs minimums sont remplis
        ArrayList<String> validNames = new ArrayList<>();
        for (int i = 0; i < playersContainer.getChildCount(); i++) {
            View row = playersContainer.getChildAt(i);
            TextInputEditText edit = row.findViewById(R.id.playerName);
            String name = edit.getText().toString().trim();

            if (TextUtils.isEmpty(name)) {
                Toast.makeText(this, "Veuillez remplir le nom du joueur " + (i + 1), Toast.LENGTH_SHORT).show();
                edit.requestFocus();
                return;
            }
            validNames.add(name);
        }

        if (validNames.size() < MIN_PLAYERS) {
            Toast.makeText(this, "Minimum " + MIN_PLAYERS + " joueurs requis", Toast.LENGTH_SHORT).show();
            return;
        }

        // Rediriger vers l'écran des paramètres
        Intent intent = new Intent(this, BoideloClassicParamsActivity.class);
        intent.putStringArrayListExtra("EXTRA_LIST_JOUEUR", validNames);
        startActivity(intent);
    }
}
