<template>
  <Modal ref="modalRef" :is-resizable="false" :modal-width="300" :modal-height="360" bg-style="none">
    <template #modalHeader>
      <h3 class="text-lg text-white">Maps</h3>
    </template>
    <template #modalBody>
      <div class="my-4 mx-auto h-full">
        <div class="text-center mb-4 px-2 flex gap-2.5">
          <button class="btn-cyan py-1.5 min-w-[calc(50%_-_5px)]" @click="fetchMaps">Refresh</button>
          <button class="btn-cyan py-1.5 min-w-[calc(50%_-_5px)]" @click="createMapModal?.open">New</button>
        </div>
        <div class="overflow-y-auto h-[calc(100%-20px)]">
          <div class="relative p-2.5 cursor-pointer flex gap-y-2.5 gap-x-5 flex-wrap" v-for="(map, index) in mapList" :key="map.id">
            <div class="absolute left-0 top-0 w-full h-px bg-gray-500" v-if="index === 0"></div>
            <div class="flex gap-3 items-center w-full" @click="() => loadMap(map.id)">
              <span>{{ map.name }}</span>
              <span class="ml-auto gap-1 flex">
                <button class="btn-red w-7 h-7 z-50 flex items-center justify-center" @click.stop="() => deleteMap(map.id)">x</button>
              </span>
            </div>
            <div class="absolute left-0 bottom-0 w-full h-px bg-gray-500"></div>
          </div>
        </div>
      </div>
    </template>
  </Modal>

  <CreateMap ref="createMapModal" @create="fetchMaps" />
</template>

<script setup lang="ts">
import type { Map, UUID } from '@/application/types'
import CreateMap from '@/components/gameMaster/mapEditor/partials/CreateMap.vue'
import Modal from '@/components/utilities/Modal.vue'
import { useMapEditorComposable } from '@/composables/useMapEditorComposable'
import { MapStorage } from '@/storage/storages'
import { useGameStore } from '@/stores/gameStore'
import { useMapEditorStore } from '@/stores/mapEditorStore'
import { onMounted, ref, useTemplateRef } from 'vue'

const gameStore = useGameStore()

const mapEditor = useMapEditorComposable()
const mapStorage = new MapStorage()
const mapList = ref<Map[]>([])
const modalRef = useTemplateRef('modalRef')
const createMapModal = useTemplateRef('createMapModal')

defineEmits(['open-create-map'])

defineExpose({
  open: () => modalRef.value?.open()
})

onMounted(async () => {
  await fetchMaps()
})

async function fetchMaps() {
  mapList.value = await mapStorage.getAll()
}

function loadMap(id: UUID) {
  gameStore.connection?.emit('gm:map:request', { mapId: id }, (response: Map) => {
    mapEditor.loadMap(response)
  })
  modalRef.value?.close()
}

async function deleteMap(id: UUID) {
  gameStore.connection?.emit('gm:map:delete', { mapId: id }, async (response: boolean) => {
    if (!response) {
      gameStore.addNotification({
        title: 'Error',
        message: 'Failed to delete map.'
      })
      return
    }

    await mapStorage.delete(id)
    await fetchMaps()
  })
}
</script>
