import { MapScene } from "../scene/map.scene";
import { GameService } from "../service/game.service";
import { PlanetUi } from "../ui/planet.ui";
import { FlightMode, Ship } from "./ships/ship.model";

export class ShipUi extends Phaser.Physics.Arcade.Sprite {
  private velocity = new Phaser.Math.Vector2(0, 0);
  private target: PlanetUi | null = null;
  private targetVector: Phaser.Math.Vector2 | null = null; // Später Planet!
  public model: Ship;
  public gameService: GameService;

  private orbitAngle: number = 0;
  private orbitRadius: number = 120;
  private orbitSpeed: number = Math.PI / 25; // Eine Runde in 2 Sekunden

  constructor(scene: MapScene, x: number, y: number, gameService: GameService, ship: Ship) {
    super(scene, x, y, ship.texture);
    this.gameService = gameService;
    this.model = ship;

    scene.add.existing(this);
    scene.physics.add.existing(this);
    this.setOrigin(0.5);
    this.setScale(1); // oder z. B. 0.5 je nach Bildgröße
    this.setDisplaySize(96, 128)
    this.setCollideWorldBounds(true);
    const conf: Phaser.Types.Input.InputConfiguration = {
      useHandCursor: true
    }
    this.setInteractive(conf)
    this.activateRoute();

    this.on('pointerdown', (pointer: Phaser.Input.Pointer) => {
      if (pointer.button == Phaser.Input.MOUSE_DOWN) {
        this.gameService.showShip(this.model);
      } else if (pointer.button == Phaser.Input.MOUSE_UP) {
       
      }
    });
  }

  

  moveTo(target: PlanetUi | undefined) {
    if (!target) { return; }
    this.target = target;
    this.targetVector = new Phaser.Math.Vector2(target.getWorldPoint().x, target.getWorldPoint().y);
    this.model.status = 'traveling';
    if (!this.body) { return; }
  }

  override update(time: number, delta: number): void {
    if (!this.target) { return; }
    if (!this.targetVector) return;
    if (!(this.body instanceof Phaser.Physics.Arcade.Body)) { return; }
    const dt = delta / 1000; // ms → Sekunden
    const from = this.getWorldPoint();
    const to = this.target.getWorldPoint();
    const distance = Phaser.Math.Distance.Between(from.x, from.y, to.x, to.y);

    switch (this.model.flightMode) {
      case FlightMode.Normal: 
        if (distance < (this.target.height / 2) + 100) {
          this.startOrbit(this.target);
          return;
        }
        this.flyDirectlyToTarget(to, dt);
        break;
      case FlightMode.Orbiting:
        this.updateOrbit(to, dt);
        break;
      case FlightMode.Docking:
        this.flyDirectlyToTarget(to, dt);
        if (distance < 150) {
          this.land();
        }
        break;
      case FlightMode.Undocking:
        if (distance > 160) {
          this.model.flightMode = FlightMode.Normal;
        }
    }
    
  }

  startOrbit(planet: PlanetUi) {
    this.model.flightMode = FlightMode.Orbiting;
    const from = this.getWorldPoint();
    const to = planet.getWorldPoint();

    // Starte Orbit am aktuellen Winkel zum Planeten
    this.orbitAngle = Phaser.Math.Angle.Between(to.x, to.y, from.x, from.y);

  }

  flyDirectlyToTarget(target: any, dt: any) {
    if (!(this.body instanceof Phaser.Physics.Arcade.Body)) { return; }
    const angle = Phaser.Math.Angle.Between(this.getWorldPoint().x, this.getWorldPoint().y, target.x, target.y);

    // Sanfte Beschleunigung
    this.model.currentSpeed = Phaser.Math.Clamp(this.model.currentSpeed + this.model.acceleration * dt, 0, this.model.maxSpeed);

    this.velocity.set(Math.cos(angle) * this.model.currentSpeed, Math.sin(angle) * this.model.currentSpeed);
    this.body.setVelocity(this.velocity.x, this.velocity.y);
    this.setRotation(this.velocity.angle() + Phaser.Math.DegToRad(90));
  }

  private updateOrbit(center: Phaser.Math.Vector2, dt: number): void {
    if (!(this.body instanceof Phaser.Physics.Arcade.Body)) { return; }
    this.orbitAngle += this.orbitSpeed * dt;
  
    const targetX = center.x + Math.cos(this.orbitAngle) * this.target!.height / 2;
    const targetY = center.y + Math.sin(this.orbitAngle) * this.target!.height / 2;
  
    const desiredVelocityX = (targetX - this.getWorldPoint().x) * 5;
    const desiredVelocityY = (targetY - this.getWorldPoint().y) * 5;
    this.body.setVelocity(desiredVelocityX, desiredVelocityY);
  
    this.setRotation(this.body.velocity.angle() + Phaser.Math.DegToRad(90));
  
    // Umdrehungen zählen
    if (this.orbitAngle >= Math.PI * 2) {
      this.orbitAngle -= Math.PI * 2;
    }
  
    if (this.target?.model.shipCanDock(this.model)) {
      this.startDocking();
    }
  }

  private startDocking() {
    this.model.flightMode = FlightMode.Docking;
    // this.currentSpeed = 0;
  }

  private land() {
    if (!(this.body instanceof Phaser.Physics.Arcade.Body)) { return; }
    if (!this.target) { return; }
    this.body.setVelocity(0, 0);
    this.velocity.set(0, 0);
    this.model.flightMode = FlightMode.Docked;
    this.targetReached(this.target); // Deine Dock-Funktion
    this.model.currentSpeed = 0;
  }

  async targetReached(target: PlanetUi) {
    
    await this.model.exchangeGoods(target.model)
    if (this.model.route) {
      this.model.route.routePointReached();
      const newTarget = (this.scene as MapScene).getPlanetUiByName(this.model.route.nextPlanetName);
      setTimeout(() => {
        this.model.flightMode = FlightMode.Undocking;
        this.model.undock(target.model)
        this.moveTo(newTarget);
      }, 1000)
    }
  }


  activateRoute() {
    if (!this.model.route) { return; }

    const planet = (this.scene as MapScene).getPlanetUiByName(this.model.route.nextPlanetName);
    this.moveTo(planet)
  }


}


