package com.example.boidelov3.games.game89;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
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.dialog.MaterialAlertDialogBuilder;

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

/**
 * Assistant pour le jeu 89++ - Affiche les défis et gère le timer
 * Les joueurs jouent avec de vraies cartes, l'application est juste un assistant
 */
public class Game89GameActivity extends AppCompatActivity {
    
    // UI Components
    private MaterialToolbar toolbar;
    private TextView timerTextView;
    private TextView challengeTitleTextView;
    private TextView challengeDescriptionTextView;
    private View challengeContainer;
    private MaterialButton recordDrinksButton;
    private MaterialButton showStatsButton;
    
    // Game Data
    private List<Game89Player> players;
    private Game89ChallengeManager challengeManager;
    private int challengeTimerMinutes;
    private CountDownTimer challengeTimer;
    private long timeUntilNextChallenge;
    private Game89ChallengeManager.Challenge currentChallenge;
    private boolean challengeActive = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game89_game);
        
        // Get intent data
        ArrayList<String> playerNames = getIntent().getStringArrayListExtra("PLAYERS");
        challengeTimerMinutes = getIntent().getIntExtra("CHALLENGE_TIMER_MINUTES", 1);
        
        if (playerNames == null || playerNames.isEmpty()) {
            finish();
            return;
        }
        
        initViews();
        setupToolbar();
        setupGame(playerNames);
        setupListeners();
        startChallengeTimer();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        timerTextView = findViewById(R.id.timerTextView);
        challengeTitleTextView = findViewById(R.id.challengeTitleTextView);
        challengeDescriptionTextView = findViewById(R.id.challengeDescriptionTextView);
        challengeContainer = findViewById(R.id.challengeContainer);
        recordDrinksButton = findViewById(R.id.recordDrinksButton);
        showStatsButton = findViewById(R.id.showStatsButton);
    }
    
    private void setupToolbar() {
        toolbar.setNavigationOnClickListener(v -> finish());
    }
    
    private void setupGame(ArrayList<String> playerNames) {
        players = new ArrayList<>();
        for (String name : playerNames) {
            players.add(new Game89Player(name));
        }
        
        challengeManager = new Game89ChallengeManager();
        
        // Show initial state
        challengeContainer.setVisibility(View.GONE);
        timerTextView.setText("En attente du premier défi...");
    }
    
    private void setupListeners() {
        recordDrinksButton.setOnClickListener(v -> showRecordDrinksDialog());
        showStatsButton.setOnClickListener(v -> showStatsDialog());
        
        // Click on challenge to dismiss it and resume timer
        challengeContainer.setOnClickListener(v -> dismissChallenge());
    }
    
    private void startChallengeTimer() {
        // Ne pas démarrer si un défi est actif
        if (challengeActive) {
            return;
        }
        
        timeUntilNextChallenge = challengeTimerMinutes * 60 * 1000L;
        
        challengeTimer = new CountDownTimer(timeUntilNextChallenge, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // Arrêter le tick si un défi est devenu actif
                if (challengeActive) {
                    cancel();
                    return;
                }
                
                timeUntilNextChallenge = millisUntilFinished;
                long minutes = millisUntilFinished / 60000;
                long seconds = (millisUntilFinished % 60000) / 1000;
                timerTextView.setText(String.format(Locale.getDefault(), 
                    "Prochain défi dans: %d:%02d", minutes, seconds));
            }
            
            @Override
            public void onFinish() {
                // Ne déclencher que si aucun défi n'est actif
                if (!challengeActive) {
                    triggerChallenge();
                    startChallengeTimer(); // Restart timer for next challenge
                }
            }
        }.start();
    }
    
    private void triggerChallenge() {
        currentChallenge = challengeManager.getRandomChallenge();
        if (currentChallenge == null) return;
        
        challengeActive = true;
        
        // Pause the timer
        if (challengeTimer != null) {
            challengeTimer.cancel();
        }
        
        // Update UI - Hide timer text when challenge is active
        timerTextView.setVisibility(View.GONE);
        challengeContainer.setVisibility(View.VISIBLE);
        challengeTitleTextView.setText(currentChallenge.getTitle());
        challengeDescriptionTextView.setText(currentChallenge.getDescription());
        
        // Vibrate to alert players
        try {
            android.os.Vibrator vibrator = (android.os.Vibrator) getSystemService(android.content.Context.VIBRATOR_SERVICE);
            if (vibrator != null) {
                vibrator.vibrate(new long[]{0, 300, 200, 300}, -1);
            }
        } catch (Exception e) {
            // Ignore vibration errors
        }
    }
    
    private void dismissChallenge() {
        challengeContainer.setVisibility(View.GONE);
        challengeActive = false;
        timerTextView.setVisibility(View.VISIBLE);
        
        // Resume the timer
        startChallengeTimer();
    }
    
    private void showRecordDrinksDialog() {
        if (players.isEmpty()) return;
        
        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
        builder.setTitle("Enregistrer des gorgées");
        
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(50, 40, 50, 10);
        
        // Create player selection
        String[] playerNames = new String[players.size()];
        for (int i = 0; i < players.size(); i++) {
            playerNames[i] = players.get(i).getName();
        }
        
        final int[] selectedPlayer = {0};
        
        TextView label = new TextView(this);
        label.setText("Sélectionnez le joueur:");
        label.setPadding(0, 0, 0, 20);
        layout.addView(label);
        
        // Create a grid of buttons for each player
        GridLayout playerGrid = new GridLayout(this);
        playerGrid.setColumnCount(2);
        
        for (int i = 0; i < players.size(); i++) {
            final int playerIndex = i;
            MaterialButton playerButton = new MaterialButton(this);
            playerButton.setText(players.get(i).getName());
            playerButton.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
            ));
            
            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.setMargins(8, 8, 8, 8);
            playerButton.setLayoutParams(params);
            
            playerButton.setOnClickListener(v -> {
                selectedPlayer[0] = playerIndex;
                showGorgeesCountDialog(playerIndex);
            });
            
            playerGrid.addView(playerButton);
        }
        
        layout.addView(playerGrid);
        
        builder.setView(layout);
        builder.setNegativeButton("Fermer", null);
        builder.show();
    }
    
    private void showGorgeesCountDialog(int playerIndex) {
        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
        builder.setTitle("Gorgées pour " + players.get(playerIndex).getName());
        
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(60, 50, 60, 20);
        
        // Label pour afficher la valeur actuelle
        TextView valueLabel = new TextView(this);
        valueLabel.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        valueLabel.setTextSize(24);
        valueLabel.setText("1 gorgée");
        valueLabel.setPadding(0, 0, 0, 20);
        layout.addView(valueLabel);
        
        // SeekBar de 1 à 8
        SeekBar seekBar = new SeekBar(this);
        seekBar.setMax(7); // 0-7, donc 1-8 avec le +1
        seekBar.setProgress(0); // Commence à 1 (0 + 1)
        seekBar.setPadding(0, 0, 0, 20);
        
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int value = progress + 1; // 1-8
                valueLabel.setText(value + " gorgée" + (value > 1 ? "s" : ""));
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
        
        layout.addView(seekBar);
        
        builder.setView(layout);
        
        builder.setPositiveButton("Valider", (dialog, which) -> {
            int count = seekBar.getProgress() + 1; // 1-8
            players.get(playerIndex).addGorgees(count);
            Toast.makeText(this, 
                players.get(playerIndex).getName() + " boit " + count + " gorgée(s)!", 
                Toast.LENGTH_SHORT).show();
        });
        
        builder.setNegativeButton("Annuler", null);
        builder.show();
    }
    
    private void showStatsDialog() {
        MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this);
        builder.setTitle("Statistiques des gorgées");
        
        StringBuilder stats = new StringBuilder();
        for (Game89Player player : players) {
            stats.append(player.getName())
                  .append(": ")
                  .append(player.getTotalGorgees())
                  .append(" gorgée(s)\n\n");
        }
        
        builder.setMessage(stats.toString());
        builder.setPositiveButton("Fermer", null);
        builder.show();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (challengeTimer != null) {
            challengeTimer.cancel();
        }
    }
}
