<template>
  <Teleport to="body">
    <Modal v-if="isModalOpen" @modal:close="() => zoneEditorStore.isObjectListModalShown = false" :isModalOpen="true" :modal-width="645" :modal-height="260">
      <template #modalHeader>
        <h3 class="text-lg">Objects</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>
              <label class="mb-1.5 font-titles hidden" for="depth">Depth</label>
              <input v-model="objectDepth" @mousedown.stop class="input-cyan" type="number" name="depth" placeholder="Depth" />
            </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-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="zoneEditorStore.setSelectedObject(object)"
                  :class="{
                    'cursor-pointer transition-all duration-300': true,
                    'border-cyan shadow-lg scale-105': zoneEditorStore.selectedObject?.id === object.id,
                    'border-transparent hover:border-gray-300': zoneEditorStore.selectedObject?.id !== object.id
                  }"
                />
              </div>
            </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 { Object } from '@/types'

const gameStore = useGameStore()
const isModalOpen = ref(false)
const zoneEditorStore = useZoneEditorStore()
const searchQuery = ref('')
const objectDepth = ref(0)
const selectedTags = ref<string[]>([])

watch(objectDepth, (depth) => {
  zoneEditorStore.setObjectDepth(depth)
})

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

const filteredObjects = computed(() => {
  return zoneEditorStore.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 () => {
  zoneEditorStore.setObjectDepth(0)

  isModalOpen.value = true
  gameStore.connection?.emit('gm:object:list', {}, (response: Object[]) => {
    zoneEditorStore.setObjectList(response)
  })
})
</script>
