package com.example.boidelov3.games.papelito;

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.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.materialswitch.MaterialSwitch;
import com.google.android.material.textfield.TextInputEditText;

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

/**
 * Activity de configuration pour le jeu Papelito (Undercover)
 */
public class PapelitoSetupActivity extends AppCompatActivity {

    private static final int MIN_PLAYERS = 3;
    private static final int MAX_PLAYERS = 12;
    private static final int MIN_UNDERCOVERS = 1;
    private static final int MAX_UNDERCOVERS = 3;

    private LinearLayout playersContainer;
    private MaterialButton addPlayerButton;
    private MaterialButton startGameButton;
    private SeekBar undercoverSeekBar;
    private TextView undercoverText;
    private MaterialSwitch mrWhiteSwitch;
    private MaterialToolbar toolbar;

    private static final int DEFAULT_DISCUSSION_TIME_SECONDS = 120; // 2 minutes par défaut
    private final List<String> playerNames = new ArrayList<>();
    private int undercoverCount = 1;
    private boolean mrWhiteEnabled = false;

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

        initViews();
        setupToolbar();
        setupListeners();

        // Ajouter 3 joueurs par défaut
        addPlayerRow();
        addPlayerRow();
        addPlayerRow();

        updateUndercoverText();
        updatePlayerNames();
    }

    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        playersContainer = findViewById(R.id.playersContainer);
        addPlayerButton = findViewById(R.id.addPlayerButton);
        startGameButton = findViewById(R.id.startGameButton);
        undercoverSeekBar = findViewById(R.id.undercoverSeekBar);
        undercoverText = findViewById(R.id.undercoverText);
        mrWhiteSwitch = findViewById(R.id.mrWhiteSwitch);
    }

    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());

        undercoverSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                undercoverCount = progress + 1; // +1 car le SeekBar commence à 0
                updateUndercoverText();
                updateMaxUndercoverLimit();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        mrWhiteSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            mrWhiteEnabled = isChecked;
            if (isChecked) {
                // Vérifier qu'on a assez de joueurs pour Mr White
                int requiredPlayers = undercoverCount + 2; // Au moins 2 civils
                if (playerNames.size() < requiredPlayers) {
                    Toast.makeText(this,
                            "Mr White nécessite au moins " + requiredPlayers + " joueurs",
                            Toast.LENGTH_SHORT).show();
                    mrWhiteSwitch.setChecked(false);
                    mrWhiteEnabled = false;
                }
            }
        });
    }

    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();
                updateMaxUndercoverLimit();
            } 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();
        updateMaxUndercoverLimit();
    }

    /**
     * Met à jour la limite maximale d'undercovers selon le nombre de joueurs
     * Il faut toujours au moins 2 civils (plus Mr White si activé)
     */
    private void updateMaxUndercoverLimit() {
        int playerCount = playerNames.size();
        int maxAllowed;

        if (mrWhiteEnabled) {
            // Avec Mr White: max = joueurs - 2 (Mr White + 1 civil minimum)
            maxAllowed = Math.max(MIN_UNDERCOVERS, playerCount - 2);
        } else {
            // Sans Mr White: max = joueurs - 2 (2 civils minimum)
            maxAllowed = Math.max(MIN_UNDERCOVERS, playerCount - 2);
        }

        // Ajuster si nécessaire
        if (undercoverCount > maxAllowed) {
            undercoverCount = maxAllowed;
            undercoverSeekBar.setProgress(undercoverCount - 1);
            updateUndercoverText();
        }

        // Mettre à jour le max du SeekBar
        int seekBarMax = Math.min(MAX_UNDERCOVERS, maxAllowed);
        undercoverSeekBar.setMax(seekBarMax - 1); // -1 car le SeekBar commence à 0
    }

    private void updateUndercoverText() {
        String text = undercoverCount + " undercover" + (undercoverCount > 1 ? "s" : "");
        undercoverText.setText(text);
    }

    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 startGame() {
        updatePlayerNames();

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

        // Vérifier qu'on a assez de joueurs pour la configuration
        int requiredPlayers = undercoverCount + 2; // Au moins 2 civils
        if (mrWhiteEnabled) {
            requiredPlayers++; // +1 pour Mr White
        }

        if (playerNames.size() < requiredPlayers) {
            Toast.makeText(this,
                    "Configuration invalide: il faut au moins " + requiredPlayers + " joueurs",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        // Lancer l'activité de jeu
        Intent intent = new Intent(this, PapelitoGameActivity.class);
        intent.putStringArrayListExtra("PLAYERS", new ArrayList<>(playerNames));
        intent.putExtra("UNDERCOVER_COUNT", undercoverCount);
        intent.putExtra("MR_WHITE_ENABLED", mrWhiteEnabled);
        intent.putExtra("DISCUSSION_TIME", DEFAULT_DISCUSSION_TIME_SECONDS);
        startActivity(intent);
    }
}
