package com.example.boidelov3.games.game89;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SeekBar;
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.card.MaterialCardView;
import com.google.android.material.textfield.TextInputEditText;

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

/**
 * Activity de configuration pour le jeu 89++
 */
public class Game89SetupActivity extends AppCompatActivity {
    
    private static final int MIN_PLAYERS = 2;
    private static final int MAX_PLAYERS = 10;
    
    private LinearLayout playersContainer;
    private MaterialButton addPlayerButton;
    private MaterialButton startGameButton;
    private SeekBar timerSeekBar;
    private TextView timerText;
    private MaterialToolbar toolbar;
    
    private final List<String> playerNames = new ArrayList<>();
    private int challengeTimerMinutes = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game89_setup);
        
        initViews();
        setupToolbar();
        setupListeners();
        
        // Ajouter 2 joueurs par défaut
        addPlayerRow();
        addPlayerRow();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        playersContainer = findViewById(R.id.playersContainer);
        addPlayerButton = findViewById(R.id.addPlayerButton);
        startGameButton = findViewById(R.id.startGameButton);
        timerSeekBar = findViewById(R.id.timerSeekBar);
        timerText = findViewById(R.id.timerText);
    }
    
    private void setupToolbar() {
        toolbar.setNavigationOnClickListener(v -> finish());
    }
    
    private void setupListeners() {
        addPlayerButton.setOnClickListener(v -> {
            if (playerNames.size() < MAX_PLAYERS) {
                addPlayerRow();
            } else {
                Toast.makeText(this, "Maximum " + MAX_PLAYERS + " joueurs", Toast.LENGTH_SHORT).show();
            }
        });
        
        startGameButton.setOnClickListener(v -> startGame());
        
        timerSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                challengeTimerMinutes = progress;
                updateTimerText();
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }
    
    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 2 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);
    }
    
    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);
            }
        }
    }
    
    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 updateStartButton() {
        int validPlayers = playerNames.size();
        boolean canStart = validPlayers >= MIN_PLAYERS;
        startGameButton.setEnabled(canStart);
        startGameButton.setText(canStart ? "JOUER (" + validPlayers + ")" : "Ajoutez des joueurs");
    }
    
    private void updateTimerText() {
        timerText.setText(challengeTimerMinutes + " minute" + (challengeTimerMinutes > 1 ? "s" : ""));
    }
    
    private void startGame() {
        updatePlayerNames();
        
        if (playerNames.size() < MIN_PLAYERS) {
            Toast.makeText(this, "Minimum " + MIN_PLAYERS + " joueurs requis", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Intent intent = new Intent(this, Game89GameActivity.class);
        intent.putStringArrayListExtra("PLAYERS", new ArrayList<>(playerNames));
        intent.putExtra("CHALLENGE_TIMER_MINUTES", challengeTimerMinutes);
        startActivity(intent);
    }
}
