import type { Map, MapObject } from '@/application/types'
import { ref } from 'vue'

export type TeleportSettings = {
  toMapId: string
  toPositionX: number
  toPositionY: number
  toRotation: number
}

const currentMap = ref<Map | null>(null)
const active = ref(false)
const tool = ref('move')
const drawMode = ref('tile')
const selectedTile = ref('')
const selectedMapObject = ref<MapObject | null>(null)
const shouldClearTiles = ref(false)
const teleportSettings = ref<TeleportSettings>({
  toMapId: '',
  toPositionX: 0,
  toPositionY: 0,
  toRotation: 0
})

export function useMapEditorComposable() {
  const loadMap = (map: Map) => {
    currentMap.value = map
  }

  const updateProperty = <K extends keyof Map>(property: K, value: Map[K]) => {
    if (currentMap.value) {
      currentMap.value[property] = value
    }
  }

  const clearMap = () => {
    if (!currentMap.value) return
    currentMap.value.placedMapObjects = []
    currentMap.value.mapEventTiles = []
    currentMap.value.tiles = []
  }

  const toggleActive = () => {
    if (active.value) reset()
    active.value = !active.value
  }

  const setTool = (newTool: string) => {
    tool.value = newTool
  }

  const setDrawMode = (mode: string) => {
    drawMode.value = mode
  }

  const setSelectedTile = (tile: string) => {
    selectedTile.value = tile
  }

  const setSelectedMapObject = (object: MapObject) => {
    selectedMapObject.value = object
  }

  const setTeleportSettings = (settings: TeleportSettings) => {
    teleportSettings.value = settings
  }

  const triggerClearTiles = () => {
    shouldClearTiles.value = true
  }

  const resetClearTilesFlag = () => {
    shouldClearTiles.value = false
  }

  const reset = () => {
    tool.value = 'move'
    drawMode.value = 'tile'
    selectedTile.value = ''
    selectedMapObject.value = null
    shouldClearTiles.value = false
  }

  return {
    // State
    currentMap,
    active,
    tool,
    drawMode,
    selectedTile,
    selectedMapObject,
    shouldClearTiles,
    teleportSettings,

    // Methods
    loadMap,
    updateProperty,
    clearMap,
    toggleActive,
    setTool,
    setDrawMode,
    setSelectedTile,
    setSelectedMapObject,
    setTeleportSettings,
    triggerClearTiles,
    resetClearTilesFlag,
    reset
  }
}
