import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:werwolf/main.dart' as app;
import 'package:werwolf/screens/playerregistry.dart';
import 'package:werwolf/screens/settings.dart';
import 'package:werwolf/screens/flippingcards.dart';
import 'package:werwolf/screens/gameboard.dart';

void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  group('Werwolf Game Integration Tests', () {
    testWidgets('Complete game flow', (WidgetTester tester) async {
      app.main();
      await tester.pumpAndSettle();

      // Ensure we are on the PlayerRegistry screen
      expect(find.byType(PlayerRegistry), findsOneWidget);

      // Add players
      for (int i = 0; i < 6; i++) {
        await tester.enterText(find.byType(TextField), 'Player $i');
        await tester.testTextInput.receiveAction(TextInputAction.done);
        await tester.pumpAndSettle();
      }

      // Ensure all players are added
      for (int i = 0; i < 6; i++) {
        expect(find.text('Player $i'), findsOneWidget);
      }

      // Navigate to GameSettings screen
      await tester.tap(find.text('Spiel einstellen'));
      await tester.pumpAndSettle();
      expect(find.byType(GameSettings), findsOneWidget);

      // Ensure the number of players and wolves are displayed correctly
      expect(find.text('Anzahl der Spieler   6'), findsOneWidget);
      expect(find.text('Anzahl der Werwölfe   1'), findsOneWidget);

      // Toggle a special role
      await tester.tap(find.byType(Switch).first);
      await tester.pumpAndSettle();
      expect((tester.widget(find.byType(Switch).first) as Switch).value, true);

      // Navigate to FlipingCard screen
      await tester.tap(find.text('Spiel starten!'));
      await tester.pumpAndSettle();
      expect(find.byType(FlipingCard), findsOneWidget);

      // Flip through all players
      for (int i = 0; i < 6; i++) {
        await tester.tap(find.text('Klick um deine Rolle zu sehen!'));
        await tester.pumpAndSettle();
        await tester.tap(find.text('Nächster Spieler'));
        await tester.pumpAndSettle();
      }

      // Ensure we navigate to the game board
      await tester.tap(find.text('Spiel anfangen!'));
      await tester.pumpAndSettle();
      expect(find.byType(PlayerGridView), findsOneWidget);

      // Tap to kill a player
      await tester.tap(find.text('Player 0'));
      await tester.pumpAndSettle();
      expect(find.byIcon(Icons.close), findsOneWidget);

      // Skip phase
      await tester.tap(find.text('Tag skippen'));
      await tester.pumpAndSettle();
      expect(find.text('Nacht skippen'), findsOneWidget);
    });
  });
}
