import 'package:flame/game.dart';
import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:shitman/game/components/player.dart';
import 'package:shitman/game/components/neighborhood.dart';
import 'package:shitman/game/components/target_house.dart';
import 'package:shitman/settings/app_settings.dart';

/// Shitman Game
/// A 2D top-down "hitman" style game, but instead of assassinating people,
/// your objective is to place flaming bags of dog poop on the doorsteps of
/// your targets without getting caught.

enum GameState { mainMenu, playing, paused, gameOver, missionComplete }

class ShitmanGame extends FlameGame
    with HasKeyboardHandlerComponents, HasCollisionDetection, AppSettings {
  late Player player;
  late Neighborhood neighborhood;
  late TargetHouse targetHouse;
  late CameraComponent gameCamera;

  GameState gameState = GameState.mainMenu;
  int missionScore = 0;
  int totalMissions = 0;
  bool infiniteMode = false;

  @override
  Future<void> onLoad() async {
    await super.onLoad();
    await initSettings();

    // Setup camera
    gameCamera = CameraComponent.withFixedResolution(
      world: world,
      width: 800,
      height: 600,
    );
    camera = gameCamera;
    addAll([world]);

    // Initialize debug mode from settings
    try {
      debugMode = appSettings.getBool('game.debug_mode');
    } catch (e) {
      debugMode = false; // Fallback if settings not ready
    }
  }

  void startGame() {
    gameState = GameState.playing;
    initializeLevel();
  }

  void startInfiniteMode() {
    infiniteMode = true;
    overlays.remove('MainMenu');
    overlays.add('InGameUI');
    startGame();
  }

  void stopGame() {
    gameState = GameState.mainMenu;
    world.removeAll(world.children);
    missionScore = 0;
  }

  void pauseGame() {
    gameState = GameState.paused;
  }

  void resumeGame() {
    gameState = GameState.playing;
  }

  void initializeLevel() {
    // Clear previous level
    world.removeAll(world.children);

    // Create neighborhood
    neighborhood = Neighborhood();
    world.add(neighborhood);

    // Create target house
    targetHouse = TargetHouse();
    world.add(targetHouse);

    // Create player
    player = Player();
    world.add(player);

    // Setup camera to follow player
    gameCamera.follow(player);
  }

  void completeCurrentMission() {
    gameState = GameState.missionComplete;
    missionScore += 100;
    totalMissions++;

    if (infiniteMode) {
      // Generate new mission after delay
      Future.delayed(Duration(seconds: 2), () {
        initializeLevel();
        gameState = GameState.playing;
      });
    }
  }

  void failMission() {
    gameState = GameState.gameOver;
    // TODO: Show game over screen
  }

  @override
  KeyEventResult onKeyEvent(
    KeyEvent event,
    Set<LogicalKeyboardKey> keysPressed,
  ) {
    super.onKeyEvent(event, keysPressed);
    if (gameState != GameState.playing) return KeyEventResult.ignored;

    // Handle pause
    if (keysPressed.contains(LogicalKeyboardKey.escape)) {
      pauseGame();
      overlays.add('PauseMenu');
      return KeyEventResult.handled;
    }

    // Handle player input
    player.handleInput(keysPressed);

    // Handle action keys on key down
    if (event is KeyDownEvent) {
      player.handleAction(event.logicalKey);
    }

    return KeyEventResult.handled;
  }

  @override
  void update(double dt) {
    super.update(dt);

    // Only update game logic when playing
    if (gameState != GameState.playing) return;

    // Game-specific update logic here
  }
}
