// ===========================================================================
// FILE: lib/widgets/game_over_dialog.dart
// ===========================================================================

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../logic/game_controller.dart';
import '../core/theme_manager.dart';
import '../core/app_colors.dart';
import '../services/storage_service.dart';

class GameOverDialog extends StatelessWidget {
  const GameOverDialog({super.key});

  @override
  Widget build(BuildContext context) {
    final game = context.read<GameController>();
    final themeManager = context.read<ThemeManager>();
    final theme = themeManager.currentColors;
    final themeType = themeManager.currentThemeType;

    int red = game.board.scoreRed;
    int blue = game.board.scoreBlue;

    bool playerBeatCPU = game.isVsCPU && red > blue;

    String myName = StorageService.instance.playerName.toUpperCase();
    if (myName.isEmpty) myName = "TU";

    // --- LOGICA NOMI ---
    String nameRed = myName;
    String nameBlue = themeType == AppThemeType.cyberpunk || themeType == AppThemeType.arcade ? "VERDE" : "BLU";

    if (game.isOnline) {
      nameRed = game.onlineHostName.toUpperCase();
      nameBlue = game.onlineGuestName.toUpperCase();
    } else if (game.isVsCPU) {
      nameRed = myName;
      nameBlue = "CPU";
    }

    // --- DETERMINA IL VINCITORE ---
    String winnerText = "";
    Color winnerColor = theme.text;

    if (red > blue) {
      winnerText = "VINCE $nameRed!";
      winnerColor = theme.playerRed;
    } else if (blue > red) {
      winnerText = "VINCE $nameBlue!";
      winnerColor = theme.playerBlue;
    } else {
      winnerText = "PAREGGIO!";
      winnerColor = theme.text;
    }

    return AlertDialog(
      backgroundColor: theme.background,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(20),
        side: BorderSide(color: winnerColor.withOpacity(0.5), width: 2),
      ),
      title: Text("FINE PARTITA", textAlign: TextAlign.center, style: TextStyle(color: theme.text, fontWeight: FontWeight.bold, fontSize: 22)),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(winnerText, textAlign: TextAlign.center, style: TextStyle(fontSize: 26, fontWeight: FontWeight.w900, color: winnerColor)),
          const SizedBox(height: 20),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
            decoration: BoxDecoration(
              color: theme.text.withOpacity(0.05),
              borderRadius: BorderRadius.circular(15),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text("$nameRed: $red", style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: theme.playerRed)),
                Text("  -  ", style: TextStyle(fontSize: 18, color: theme.text)),
                Text("$nameBlue: $blue", style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: theme.playerBlue)),
              ],
            ),
          ),

          if (game.isVsCPU) ...[
            const SizedBox(height: 15),
            Text("Difficoltà CPU: Livello ${game.cpuLevel}", style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: theme.text.withOpacity(0.7))),
          ]
        ],
      ),
      actionsPadding: const EdgeInsets.only(left: 20, right: 20, bottom: 20, top: 10),
      actionsAlignment: MainAxisAlignment.center,
      actions: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            if (playerBeatCPU)
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: winnerColor,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 15),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
                  elevation: 5,
                ),
                onPressed: () {
                  Navigator.pop(context);
                  game.increaseLevelAndRestart();
                },
                child: const Text("PROSSIMO LIVELLO ➔", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
              )
            else if (game.isOnline)
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: winnerColor == theme.text ? theme.playerBlue : winnerColor,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 15),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
                  elevation: 5,
                ),
                onPressed: () {
                  Navigator.pop(context);
                  if (game.board.isGameOver) {
                    game.requestRematch();
                  }
                },
                child: const Text("RIGIOCA ONLINE", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, letterSpacing: 1.5)),
              )
            else
              ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: winnerColor == theme.text ? theme.playerBlue : winnerColor,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(vertical: 15),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
                  elevation: 5,
                ),
                onPressed: () {
                  Navigator.pop(context);
                  game.startNewGame(game.board.radius, vsCPU: game.isVsCPU);
                },
                child: const Text("RIGIOCA", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, letterSpacing: 2)),
              ),

            const SizedBox(height: 12),

            OutlinedButton(
              style: OutlinedButton.styleFrom(
                foregroundColor: theme.text,
                side: BorderSide(color: theme.text.withOpacity(0.3), width: 2),
                padding: const EdgeInsets.symmetric(vertical: 15),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
              ),
              onPressed: () {
                if (game.isOnline) {
                  game.disconnectOnlineGame();
                }
                Navigator.pop(context);
                Navigator.pop(context);
              },
              child: Text("TORNA AL MENU", style: TextStyle(fontWeight: FontWeight.bold, color: theme.text, fontSize: 14, letterSpacing: 1.5)),
            ),
          ],
        )
      ],
    );
  }
}