<template>
    <div class="h-full overflow-auto">
      <div class="flex justify-between flex-wrap gap-2.5 items-center">
        <div v-for="(mapObject, index) in filteredMapObjects" :key="index" class="max-w-1/4 inline-block">
          <img
            class="border-2 border-solid rounded max-w-full"
            :src="`${config.server_endpoint}/textures/map_objects/${mapObject.id}.png`"
            alt="Object"
            @click="mapEditor.setSelectedMapObject(mapObject)"
            :class="{
              'cursor-pointer transition-all duration-300': true,
              'border-cyan shadow-lg': mapEditor.selectedMapObject.value?.id === mapObject.id,
              'border-transparent hover:border-gray-300': mapEditor.selectedMapObject.value?.id !== mapObject.id
            }"
          />
        </div>
      </div>
    </div>
</template>

<script setup lang="ts">
import config from '@/application/config'
import type { MapObject } from '@/application/types'
import Modal from '@/components/utilities/Modal.vue'
import { useMapEditorComposable } from '@/composables/useMapEditorComposable'
import { MapObjectStorage } from '@/storage/storages'
import { liveQuery } from 'dexie'
import { computed, onMounted, onUnmounted, ref, useTemplateRef } from 'vue'

const isOpen = ref(false)
const mapObjectStorage = new MapObjectStorage()
const isModalOpen = ref(false)
const mapEditor = useMapEditorComposable()
const searchQuery = ref('')
const selectedTags = ref<string[]>([])
const mapObjectList = ref<MapObject[]>([])

defineExpose({
  open: () => (isOpen.value = true),
  close: () => (isOpen.value = false),
  toggle: () => (isOpen.value = !isOpen.value)
})

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

const filteredMapObjects = computed(() => {
  return mapObjectList.value.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)
  }
}

let subscription: any = null

onMounted(() => {
  isModalOpen.value = true
  subscription = liveQuery(() => mapObjectStorage.liveQuery()).subscribe({
    next: (result) => {
      mapObjectList.value = result
    },
    error: (error) => {
      console.error('Failed to fetch tiles:', error)
    }
  })
})

onUnmounted(() => {
  if (subscription) {
    subscription.unsubscribe()
  }
})
</script>
