import 'dart:math' as math;

import 'package:wolf_3d_data_types/wolf_3d_data_types.dart';
import 'package:wolf_3d_entities/src/entities/enemies/enemy.dart';
import 'package:wolf_3d_entities/src/entity.dart';

class Mutant extends Enemy {
  static const double speed = 0.04;
  bool _hasFiredThisCycle = false;

  static EnemyType get type => EnemyType.mutant;

  Mutant({
    required super.x,
    required super.y,
    required super.angle,
    required super.mapId,
  }) : super(spriteIndex: type.spriteBaseIdx, state: EntityState.idle) {
    health = 45;
    damage = 10;
  }

  @override
  ({Coordinate2D movement, double newAngle}) update({
    required int elapsedMs,
    required Coordinate2D playerPosition,
    required bool Function(int x, int y) isWalkable,
    required void Function(int damage) onDamagePlayer,
    required void Function(int x, int y) tryOpenDoor,
  }) {
    Coordinate2D movement = const Coordinate2D(0, 0);
    double newAngle = angle;

    checkWakeUp(
      elapsedMs: elapsedMs,
      playerPosition: playerPosition,
      isWalkable: isWalkable,
    );

    double distance = position.distanceTo(playerPosition);
    double angleToPlayer = position.angleTo(playerPosition);

    if (state != EntityState.idle && state != EntityState.dead) {
      newAngle = angleToPlayer;
    }

    // Calculate angle diff for the octant logic
    double diff = angleToPlayer - newAngle;
    while (diff <= -math.pi) {
      diff += 2 * math.pi;
    }
    while (diff > math.pi) {
      diff -= 2 * math.pi;
    }

    EnemyAnimation currentAnim = switch (state) {
      EntityState.patrolling => EnemyAnimation.walking,
      EntityState.attacking => EnemyAnimation.attacking,
      EntityState.pain => EnemyAnimation.pain,
      EntityState.dead => isDying ? EnemyAnimation.dying : EnemyAnimation.dead,
      _ => EnemyAnimation.idle,
    };

    spriteIndex = type.getSpriteFromAnimation(
      animation: currentAnim,
      elapsedMs: elapsedMs,
      lastActionTime: lastActionTime,
      angleDiff: diff,
    );

    if (state == EntityState.attacking) {
      int time = elapsedMs - lastActionTime;
      if (time >= 150 && !_hasFiredThisCycle) {
        onDamagePlayer(damage);
        _hasFiredThisCycle = true;
      } else if (time >= 300) {
        state = EntityState.patrolling;
        lastActionTime = elapsedMs;
      }
    }

    return (movement: movement, newAngle: newAngle);
  }
}
