<template>
  <Modal :isModalOpen="mapEditorStore.isObjectListModalShown" :modal-width="645" :modal-height="260" @modal:close="() => (mapEditorStore.isObjectListModalShown = false)" :bg-style="'none'">
    <template #modalHeader>
      <h3 class="text-lg text-white">Objects</h3>
    </template>
    <template #modalBody>
      <div class="flex pt-4 pl-4">
        <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-field" type="text" name="search" placeholder="Search" v-model="searchQuery" />
          </div>
        </div>
      </div>
      <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-full overflow-auto">
          <div class="flex justify-between flex-wrap gap-2.5 items-center">
            <div v-for="(object, index) in filteredObjects" :key="index" class="max-w-1/4 inline-block">
              <img
                class="border-2 border-solid max-w-full"
                :src="`${config.server_endpoint}/assets/objects/${object.id}.png`"
                alt="Object"
                @click="mapEditorStore.setSelectedObject(object)"
                :class="{
                  'cursor-pointer transition-all duration-300': true,
                  'border-cyan shadow-lg scale-105': mapEditorStore.selectedObject?.id === object.id,
                  'border-transparent hover:border-gray-300': mapEditorStore.selectedObject?.id !== object.id
                }"
              />
            </div>
          </div>
        </div>
      </div>
    </template>
  </Modal>
</template>

<script setup lang="ts">
import config from '@/application/config'
import type { MapObject, PlacedMapObject } from '@/application/types'
import Modal from '@/components/utilities/Modal.vue'
import { useGameStore } from '@/stores/gameStore'
import { useMapEditorStore } from '@/stores/mapEditorStore'
import { computed, onMounted, ref } from 'vue'

const gameStore = useGameStore()
const isModalOpen = ref(false)
const mapEditorStore = useMapEditorStore()
const searchQuery = ref('')
const selectedTags = ref<string[]>([])

const uniqueTags = computed(() => {
  const allTags = mapEditorStore.objectList.flatMap((obj) => obj.tags || [])
  return Array.from(new Set(allTags))
})

const filteredObjects = computed(() => {
  return mapEditorStore.objectList.filter((object) => {
    const matchesSearch = !searchQuery.value || object.name.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchesTags = selectedTags.value.length === 0 || (object.tags && selectedTags.value.some((tag) => object.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:mapObject:list', {}, (response: MapObject[]) => {
    mapEditorStore.setMapObjectList(response)
  })
})
</script>
