<template>
  <Modal :is-modal-open="true" @modal:close="() => zoneEditorStore.setTool('move')" :modal-width="300" :modal-height="250" :is-resizable="false">
    <template #modalHeader>
      <h3 class="m-0 font-medium shrink-0">Teleport settings</h3>
    </template>

    <template #modalBody>
      <div class="m-4">
        <form method="post" @submit.prevent="" class="inline">
          <div class="gap-2.5 flex flex-wrap">
            <div class="form-field-half">
              <label for="positionX">Position X</label>
              <input class="input-cyan" v-model="toPositionX" name="positionX" id="positionX" type="number" />
            </div>
            <div class="form-field-half">
              <label for="positionY">Position Y</label>
              <input class="input-cyan" v-model="toPositionY" name="positionY" id="positionY" type="number" />
            </div>
            <div class="form-field-full">
              <label for="toZoneId">Zone to teleport to</label>
              <select v-model="toZoneId" class="input-cyan" name="toZoneId" id="toZoneId">
                <option :value="0">Select zone</option>
                <option v-for="zone in zoneEditorStore.zoneList" :key="zone.id" :value="zone.id">{{ zone.name }}</option>
              </select>
            </div>
          </div>
        </form>
      </div>
    </template>
  </Modal>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import Modal from '@/components/utilities/Modal.vue'
import { useZoneEditorStore } from '@/stores/zoneEditor'
import { useGameStore } from '@/stores/game'
import { Zone } from '@/types'

const zoneEditorStore = useZoneEditorStore()
const gameStore = useGameStore()

onMounted(async () => {
  fetchZones()
})

function fetchZones() {
  gameStore.connection?.emit('gm:zone_editor:zone:list', {}, (response: Zone[]) => {
    zoneEditorStore.setZoneList(response)
  })
}

const toPositionX = ref(zoneEditorStore.teleportSettings.toPositionX)
const toPositionY = ref(zoneEditorStore.teleportSettings.toPositionY)
const toZoneId = ref(zoneEditorStore.teleportSettings.toZoneId)

watch(toZoneId, (value) => {
  zoneEditorStore.setTeleportSettings({
    toPositionX: toPositionX.value,
    toPositionY: toPositionY.value,
    toZoneId: value
  })
})

watch(toPositionX, (value) => {
  zoneEditorStore.setTeleportSettings({
    toPositionX: value,
    toPositionY: toPositionY.value,
    toZoneId: toZoneId.value
  })
})

watch(toPositionY, (value) => {
  zoneEditorStore.setTeleportSettings({
    toPositionX: toPositionX.value,
    toPositionY: value,
    toZoneId: toZoneId.value
  })
})
</script>
