import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../models/player.dart';
import '../models/role.dart';

// Main widget for displaying the player grid
class PlayerGridView extends StatefulWidget {
  final List<Player> players;

  const PlayerGridView({required this.players, Key? key}) : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _PlayerGridViewState createState() => _PlayerGridViewState();
}

class _PlayerGridViewState extends State<PlayerGridView> {
  bool isNight = true; // Variable to track whether it is night or day

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              isNight ? Icons.nights_stay : Icons.wb_sunny,
              size: 24,
              color: isNight ? Colors.grey[300] : Colors.yellow,
            ),
            const SizedBox(width: 10),
            Text(
              isNight ? 'Nacht' : 'Tag', // Display whether it is night or day
            ),
          ],
        ),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.info),
            onPressed: () {
              _showRolesDialog(); // Show dialog with player roles
            },
          ),
        ],
        leading: IconButton(
          icon: const Icon(FontAwesomeIcons.xmark),
          onPressed: () {
            Navigator.popUntil(context, ModalRoute.withName('/')); // Return to main screen
          },
        ),
      ),
      body: Container(
        color: isNight
            ? const Color(0xff2d2d2d)
            : const Color.fromARGB(255, 194, 216, 225), // Set background color based on night/day
        padding: const EdgeInsets.only(left: 15, right: 15),
        child: Column(
          children: [
            Expanded(
              child: GridView.builder(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount:
                      MediaQuery.of(context).size.shortestSide < 600 ? 2 : 4, // Adjust grid based on screen size
                  mainAxisSpacing: 10,
                  crossAxisSpacing: 10,
                ),
                itemCount: widget.players.length,
                itemBuilder: (context, index) {
                  widget.players[index];

                  return GestureDetector(
                    onTap: () {
                      setState(() {
                        if (!widget.players[index].isDead) {
                          _killPlayer(widget.players[index]); // Mark player as dead
                        }
                      });
                    },
                    child: Card(
                      color: widget.players[index].isDead
                          ? Colors.grey
                          : Theme.of(context).colorScheme.primary, // Change card color based on player status
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            widget.players[index].name,
                            style: const TextStyle(fontSize: 24),
                            textAlign: TextAlign.center,
                            maxLines: 3,
                            overflow: TextOverflow.ellipsis,
                          ),
                          if (widget.players[index].isDead)
                            const Icon(Icons.close,
                                color: Colors.red, size: 48), // Show icon if player is dead
                        ],
                      ),
                    ),
                  );
                },
              ),
            ),
            const Divider(
              height: 1,
              color: Colors.grey,
            ),
            Padding(
              padding: const EdgeInsets.only(bottom: 60, top: 10),
              child: ElevatedButton(
                onPressed: _changePhase, // Change phase between night and day
                child: Text(isNight ? 'Tag skippen' : 'Nacht skippen'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _killPlayer(Player player) {
    if (isNight) {
      if (player.role != Role.werwolf) {
        player.isDead = true;
        _checkWinCondition(); // Check win condition after killing player
        isNight = false;
      }
    } else {
      player.isDead = true;
      _checkWinCondition(); // Check win condition after killing player
      if (player.role == Role.joker) {
        _showWinDialog('Der Joker hat gewonnen!'); // Show win dialog for Joker
      }
      isNight = true;
    }
    setState(() {});
  }

  void _changePhase() {
    isNight = !isNight; // Toggle between night and day
    setState(() {});
  }

  void _checkWinCondition() {
    int countWolves = widget.players
        .where((player) => !player.isDead && player.role == Role.werwolf)
        .length;
    int countVillagers = widget.players
        .where((player) => !player.isDead && player.role != Role.werwolf)
        .length;

    if (countWolves == 0) {
      _showWinDialog('Die Dorfbewohner haben gewonnen!'); // Show win dialog for villagers
    } else if (countWolves >= countVillagers) {
      _showWinDialog('Die Werwölfe haben gewonnen!'); // Show win dialog for werewolves
    }
  }

  void _showWinDialog(String message) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Spielende'),
          content: Text(message),
          actions: <Widget>[
            TextButton(
              child: const Text('Spiel beenden'),
              onPressed: () {
                Navigator.popUntil(context, ModalRoute.withName('/')); // Return to main screen
              },
            ),
          ],
        );
      },
    );
  }

  void _showRolesDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Spielerrollen'),
          content: SizedBox(
            width: double.maxFinite,
            child: ListView.builder(
              shrinkWrap: true,
              itemCount: widget.players.length,
              itemBuilder: (context, index) {
                final player = widget.players[index];
                return ListTile(
                  title: Text(
                    player.name,
                    style: Theme.of(context).textTheme.labelLarge,
                  ),
                  subtitle: Text(
                    player.role.name,
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                );
              },
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('OK'),
              onPressed: () {
                Navigator.of(context).pop(); // Close dialog
              },
            ),
          ],
        );
      },
    );
  }
}
