import { PLANETCONFIGS } from "../data/planets.data";
import { TradeRoute } from "../model/routes/trade-route.model";
import { ShipUi } from "../model/ship";
import { GameService } from "../service/game.service";
import { PlanetUi } from "../ui/planet.ui";

export class MapScene extends Phaser.Scene {
  public gameService: GameService = new GameService();
  private camera!: Phaser.Cameras.Scene2D.Camera;
  private isDragging = false;
  private dragStart = new Phaser.Math.Vector2();
  private ship!: ShipUi; // Das Raumschiff
  private ships: ShipUi[] = [];
  private planets: PlanetUi[] = [];


  private lastZoomTime = 0;

  constructor() {
    super({ key: 'MapScene '})
  }

  preload() {
    this.load.image('swift-hauler', 'sprites/ships/swift-hauler.png');
    this.load.image('colony-carrier', 'sprites/ships/colony-carrier.png');
    this.load.image('industrial-tanker', 'sprites/ships/industrial-tanker.png');
    this.load.image('harbour', 'sprites/buildings/harbour.png');
    this.load.image('planet', 'sprites/planets/planet-1.png');
    this.load.image('terra-nova', 'sprites/planets/terra-nova.png');
    this.load.image('volaris', 'sprites/planets/volaris.png');
    this.load.image('ignis-prime', 'sprites/planets/ignis-prime.png');
    this.load.image('mechanica-prime', 'sprites/planets/mechanica-prime.png');
    this.load.image('novus-reach', 'sprites/planets/novus-reach.png');
    this.load.image('aqualis', 'sprites/planets/aqualis.png');
    this.load.image('ferron', 'sprites/planets/ferron.png');
  }

  create() {
    this.camera = this.cameras.main;

    this.createPlaceHolderGraphic();
    // this.camera.setBackgroundColor('0x99ccff')

    // Weltgröße groß setzen, z. B. 5000x5000 Pixel
    this.camera.setBounds(0, 0, 10000, 10000);
    this.physics.world.setBounds(0, 0, 10000, 10000);
    this.cameras.main.setBounds(0, 0, 10000, 10000);


    /* Sterne */
    for (let i = 0; i< 1000; i++) {
      const x = Phaser.Math.Between(0, 10000);
      const y = Phaser.Math.Between(0, 10000);
      this.add.circle(x, y, Phaser.Math.Between(2, 10), 0x88ccff)
    }

    // Beispiel: ein paar Kreise (Planeten) zeichnen
    this.buildPlanets();

    // Events für Panning
    this.input.on('pointerdown', (pointer: Phaser.Input.Pointer) => {
      if (!this.gameService.canDrag) { return; }
      this.isDragging = true;
      
      this.dragStart.set(pointer.x, pointer.y);
    });

    this.input.on('pointerup', () => {
      this.isDragging = false;
    });

    this.input.on('pointermove', (pointer: Phaser.Input.Pointer) => {
      if (!this.isDragging || !this.gameService.canDrag) return;
      const dragX = pointer.x - this.dragStart.x;
      const dragY = pointer.y - this.dragStart.y;
      this.camera.scrollX -= dragX / this.camera.zoom;
      this.camera.scrollY -= dragY / this.camera.zoom;
      this.dragStart.set(pointer.x, pointer.y);
    });

    // Zoom via Mausrad
    this.input.on('wheel', (_: any, __: number, ___: number, deltaY: number) => {
      const now = Date.now();
      if (now - this.lastZoomTime < 50) return; // nur alle 100ms
      this.lastZoomTime = now;
      const factor = 1.1;
      if (deltaY > 0) {
        this.camera.setZoom(this.camera.zoom / factor);
      } else {
        this.camera.setZoom(this.camera.zoom * factor);
      }

      const minScale = Math.max(window.innerWidth / 10000, window.innerHeight / 10000)
      // Begrenze Zoom
      this.camera.setZoom(Phaser.Math.Clamp(this.camera.zoom, minScale, 1));
    });

    this.camera.setZoom(0.4)



    this.gameService.onShipCreate.subscribe(ship => {
      const ui = new ShipUi(this, 100, 100, this.gameService, ship);
      ui.activateRoute();
      this.physics.world.enable(ui);
      this.ships.push(ui);
    })

    this.gameService.onShipDestroy.subscribe(ship => {
      const ui = this.ships.find(i => i.model = ship);
      if (ui) {
        ui.destroy();
      }
      this.ships = this.ships.filter(s => s != ui);
    })
    // this.enableMouseLogging();
    
  }


  override update(time: number, delta: number): void {
    if (this.ship) {

      this.ship.update(time, delta);
    }

    for (let ship of this.ships) {
        ship.update(time, delta)
    }
  }
  private buildPlanets() {
    for (let config of PLANETCONFIGS) {
      const planet = new PlanetUi(this, config.x, config.y, config.texture, config.config, this.gameService);
      planet.rightClick.subscribe(planet => {
        this.ship.moveTo(planet);
        this.isDragging = false;
      });
      planet.leftClick.subscribe(planet => {
        this.gameService.showDialog(planet.model);
        this.isDragging = false;
      });
      this.planets.push(planet);
      this.gameService.planets.push(planet.model);
    }
  }

  private createPlaceHolderGraphic() {
    const graphics = this.add.graphics();
    graphics.fillStyle(0x88ccff, 1);
    graphics.fillCircle(100, 100, 100);
    graphics.generateTexture('planet', 200, 200);
    graphics.destroy();
  }

  getPlanetUiByName(name: string) {
    return this.planets.find(p => p.model.name == name);
  }

  enableMouseLogging() {
    let mouseText: Phaser.GameObjects.Text;

    this.input.on('pointermove', (pointer: Phaser.Input.Pointer) => {
        if (!mouseText) {
            mouseText = this.add.text(30, 30, '', {
                fontSize: '160px',
                color: '#00ff00',
                backgroundColor: '#000000',
                padding: { x: 5, y: 2 }
            }).setScrollFactor(0).setDepth(9999);
        }
        mouseText.setText(`X: ${pointer.worldX.toFixed(0)}\nY: ${pointer.worldY.toFixed(0)}`);
    });
  }
}