<template>
  <CreateZone @submit="fetchZones" 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">
            <button class="btn-cyan py-1.5 min-w-full" @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 zones" :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 { useSocketStore } from '@/stores/socket'
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 socket = useSocketStore()
const zoneEditorStore = useZoneEditorStore()
const zones = ref([] as Zone[])

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

function fetchZones() {
  socket.connection.emit('gm:zone_editor:zone:list', {}, (response: Zone[]) => {
    zones.value = response
  })
}

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

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