<template>
  <Modal ref="modalRef" :modal-width="300" :modal-height="420" :is-resizable="false" bg-style="none">
    <template #modalHeader>
      <h3 class="m-0 font-medium shrink-0 text-white">Create new map</h3>
    </template>
    <template #modalBody>
      <div class="m-4">
        <form method="post" @submit.prevent="submit" class="inline">
          <div class="gap-2.5 flex flex-wrap">
            <div class="form-field-full">
              <label for="name">Name</label>
              <input class="input-field max-w-64" v-model="name" name="name" id="name" />
            </div>
            <div class="form-field-half">
              <label for="name">Width</label>
              <input class="input-field max-w-64" v-model="width" name="width" id="width" type="number" />
            </div>
            <div class="form-field-half">
              <label for="name">Height</label>
              <input class="input-field max-w-64" v-model="height" name="height" id="height" type="number" />
            </div>
            <div class="form-field-full">
              <label for="name">PVP enabled</label>
              <select class="input-field" v-model="pvp" name="pvp" id="pvp">
                <option :value="false">No</option>
                <option :value="true">Yes</option>
              </select>
            </div>
          </div>
          <button class="btn-cyan px-4 py-1.5 min-w-24" type="submit">Save</button>
        </form>
      </div>
    </template>
  </Modal>
</template>

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

const emit = defineEmits(['create'])

const gameStore = useGameStore()
const mapStorage = new MapStorage()
const modalRef = useTemplateRef('modalRef')

const name = ref('')
const width = ref(0)
const height = ref(0)
const pvp = ref(false)

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

async function submit() {
  gameStore.connection?.emit('gm:map:create', { name: name.value, width: width.value, height: height.value }, async (response: Map | false) => {
    if (!response) {
      return
    }

    // Reset form
    name.value = ''
    width.value = 0
    height.value = 0
    pvp.value = false

    // Add map to storage
    await mapStorage.add(response)

    // Let list know to fetch new maps
    emit('create')
  })

  // Close modal
  modalRef.value?.close()
}
</script>
