import { computed, type Ref, ref } from 'vue'
import { getTile, tileToWorldXY } from '@/services/zone'
import { useZoneEditorStore } from '@/stores/zoneEditor'
import config from '@/config'

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

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

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

  function dragZone(pointer: Phaser.Input.Pointer) {
    if (isDragging.value) {
      const { x, y, prevPosition } = pointer
      const { scrollX, scrollY, zoom } = camera.value
      camera.value.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({ event, deltaY }: Phaser.Input.Pointer) {
    if (event instanceof WheelEvent && event.shiftKey) {
      scene.scale.setZoom(scene.scale.zoom - deltaY * 0.01)
      camera.value = scene.cameras.main
    }
  }

  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 }
}
