<template>
  <Teleport to="body">
    <Modal v-if="isModalOpen" @modal:close="() => zoneEditorStore.setTool('move')" :isModalOpen="true" :modal-width="645" :modal-height="260">
      <template #modalHeader>
        <h3 class="text-lg">Tiles</h3>
        <div class="flex">
          <div class="w-full flex gap-1.5 flex-row">
            <div>
              <label class="mb-1.5 font-titles hidden" for="search">Search...</label>
              <input @mousedown.stop class="input-cyan" type="text" name="search" placeholder="Search" v-model="searchQuery" />
            </div>
          </div>
        </div>
      </template>
      <template #modalBody>
        <div class="m-[15px]">
          <div class="flex justify-between flex-wrap gap-2.5 items-center">
            <div v-for="(tile, index) in filteredTiles" :key="index" class="max-w-[25%] inline-block">
              <img
                class="border-2 border-solid max-w-full"
                :src="`${config.server_endpoint}/assets/tiles/${tile.id}.png`"
                alt="Tile"
                @click="zoneEditorStore.setSelectedTile(tile)"
                :class="{
                  'cursor-pointer transition-all duration-300': true,
                  'border-cyan shadow-lg scale-105': zoneEditorStore.selectedTile?.id === tile.id,
                  'border-transparent hover:border-gray-300': zoneEditorStore.selectedTile?.id !== tile.id
                }"
              />
            </div>
          </div>
        </div>
      </template>
    </Modal>
  </Teleport>
</template>

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

const gameStore = useGameStore()
const isModalOpen = ref(false)
const zoneEditorStore = useZoneEditorStore()
const searchQuery = ref('')

const filteredTiles = computed(() => {
  if (!searchQuery.value) {
    return zoneEditorStore.tileList
  }
  return zoneEditorStore.tileList.filter((tile) => tile.name.toLowerCase().includes(searchQuery.value.toLowerCase()))
})

onMounted(async () => {
  isModalOpen.value = true
  gameStore.connection.emit('gm:tile:list', {}, (response: Tile[]) => {
    zoneEditorStore.setTileList(response)
  })
})
</script>
