import { computed, type Ref } from 'vue'
import { getTile, tileToWorldXY } from '@/composables/zoneComposable'
import { useZoneEditorStore } from '@/stores/zoneEditorStore'
import { useGameStore } from '@/stores/gameStore'
import config from '@/config'

export function useZoneEditorPointerHandlers(scene: Phaser.Scene, layer: Phaser.Tilemaps.TilemapLayer, waypoint: Ref<{ visible: boolean; x: number; y: number }>, camera: Phaser.Cameras.Scene2D.Camera) {
  const gameStore = useGameStore()
  const zoneEditorStore = useZoneEditorStore()
  const isMoveTool = computed(() => zoneEditorStore.tool === 'move')

  function updateWaypoint(pointer: Phaser.Input.Pointer) {
    const { x: px, y: py } = camera.getWorldPoint(pointer.x, pointer.y)
    const pointerTile = getTile(layer, px, py)

    if (pointerTile) {
      const worldPoint = tileToWorldXY(layer, pointerTile.x, pointerTile.y)
      waypoint.value = {
        visible: true,
        x: worldPoint.positionX,
        y: worldPoint.positionY + config.tile_size.y + 15
      }
    } else {
      waypoint.value.visible = false
    }
  }

  function dragZone(pointer: Phaser.Input.Pointer) {
    if (gameStore.game.isPlayerDraggingCamera) {
      const { x, y, prevPosition } = pointer
      const { scrollX, scrollY, zoom } = camera
      camera.setScroll(scrollX - (x - prevPosition.x) / zoom, scrollY - (y - prevPosition.y) / zoom)
    }
  }

  function handlePointerMove(pointer: Phaser.Input.Pointer) {
    if (isMoveTool.value || pointer.event.shiftKey) {
      dragZone(pointer)
    }
    updateWaypoint(pointer)
  }

  function handleZoom(pointer: Phaser.Input.Pointer) {
    if (pointer.event instanceof WheelEvent && pointer.event.shiftKey) {
      const deltaY = pointer.event.deltaY
      let zoomLevel = camera.zoom - deltaY * 0.005
      if (zoomLevel > 0 && zoomLevel < 3) {
        camera.setZoom(zoomLevel)
      }
    }
  }

  const setupPointerHandlers = () => {
    scene.input.on(Phaser.Input.Events.POINTER_MOVE, handlePointerMove)
    scene.input.on(Phaser.Input.Events.POINTER_WHEEL, handleZoom)
  }

  const cleanupPointerHandlers = () => {
    scene.input.off(Phaser.Input.Events.POINTER_MOVE, handlePointerMove)
    scene.input.off(Phaser.Input.Events.POINTER_WHEEL, handleZoom)
  }

  return { setupPointerHandlers, cleanupPointerHandlers }
}
