<template>
  <CreateZone v-if="zoneEditorStore.isCreateZoneModalShown" />

  <Teleport to="body">
    <Modal @modal:close="() => zoneEditorStore.toggleZoneListModal()" :is-resizable="false" :is-modal-open="true" :modal-width="300" :modal-height="360">
      <template #modalHeader>
        <h3 class="text-lg">Zones</h3>
      </template>
      <template #modalBody>
        <div class="my-[15px] mx-auto">
          <div class="text-center mb-4 px-2 flex justify-around">
            <button class="btn-cyan py-1.5 min-w-[48%]" @click="fetchZones">Refresh</button>
            <button class="btn-cyan py-1.5 min-w-[48%]" @click="() => zoneEditorStore.toggleCreateZoneModal()">New</button>
          </div>
          <div class="relative p-2.5 cursor-pointer flex gap-y-2.5 gap-x-5 flex-wrap" v-for="(zone, index) in zoneEditorStore.zoneList" :key="zone.id">
            <div class="absolute left-0 top-0 w-full h-[1px] bg-cyan-200" v-if="index === 0"></div>
            <div class="flex gap-3 items-center w-full">
              <span @click="() => loadZone(zone.id)">{{ zone.name }}</span>
              <span class="ml-auto gap-1 flex">
                <button class="btn-bordeaux py-0.5 px-2.5" @click="() => deleteZone(zone.id)">X</button>
              </span>
            </div>
            <div class="absolute left-0 bottom-0 w-full h-[1px] bg-cyan-200"></div>
          </div>
        </div>
      </template>
    </Modal>
  </Teleport>
</template>

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

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

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

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

function loadZone(id: number) {
  console.log('loadZone', id)
  gameStore.connection.emit('gm:zone_editor:zone:request', { zoneId: id }, (response: Zone) => {
    zoneEditorStore.setZone(response)
  })
  zoneEditorStore.toggleZoneListModal()
}

function deleteZone(id: number) {
  gameStore.connection.emit('gm:zone_editor:zone:delete', { zoneId: id }, () => {
    fetchZones()
  })
}
</script>
