<template>
  <Teleport to="body">
    <Modal v-if="isModalOpen" @modal:close="() => (zoneEditorStore.isTileListModalShown = false)" :isModalOpen="true" :modal-width="645" :modal-height="600">
      <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="flex flex-col h-full p-4">
          <div class="mb-4 flex flex-wrap gap-2">
            <button v-for="tag in uniqueTags" :key="tag" @click="toggleTag(tag)" class="btn-cyan" :class="{ 'opacity-50': !selectedTags.includes(tag) }">
              {{ tag }}
            </button>
          </div>
          <div class="h-[calc(100%_-_60px)] flex-grow overflow-y-auto">
            <div class="grid grid-cols-8 gap-2 justify-items-center">
              <div v-for="tile in filteredTiles" :key="tile.id" class="flex items-center justify-center">
                <img
                  class="max-w-full max-h-full border-2 border-solid"
                  :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>
        </div>
      </template>
    </Modal>
  </Teleport>
</template>

<script setup lang="ts">
import config from '@/config'
import { ref, onMounted, computed } 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 selectedTags = ref<string[]>([])

const uniqueTags = computed(() => {
  const allTags = zoneEditorStore.tileList.flatMap((tile) => tile.tags || [])
  return Array.from(new Set(allTags))
})

const filteredTiles = computed(() => {
  return zoneEditorStore.tileList.filter((tile) => {
    const matchesSearch = !searchQuery.value || tile.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesTags = selectedTags.value.length === 0 || (tile.tags && selectedTags.value.some((tag) => tile.tags.includes(tag)))
    return matchesSearch && matchesTags
  })
})

const toggleTag = (tag: string) => {
  if (selectedTags.value.includes(tag)) {
    selectedTags.value = selectedTags.value.filter((t) => t !== tag)
  } else {
    selectedTags.value.push(tag)
  }
}

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