<template>
  <Modal ref="modalRef" :modal-width="645" :modal-height="260" :bg-style="'none'">
    <template #modalHeader>
      <h3 class="text-lg text-white">Map 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="(mapObject, index) in filteredMapObjects" :key="index" class="max-w-1/4 inline-block">
              <img
                class="border-2 border-solid 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 scale-105': mapEditor.selectedMapObject.value?.id === mapObject.id,
                  'border-transparent hover:border-gray-300': mapEditor.selectedMapObject.value?.id !== mapObject.id
                }"
              />
            </div>
          </div>
        </div>
      </div>
    </template>
  </Modal>
</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 mapObjectStorage = new MapObjectStorage()
const isModalOpen = ref(false)
const mapEditor = useMapEditorComposable()
const searchQuery = ref('')
const selectedTags = ref<string[]>([])
const mapObjectList = ref<MapObject[]>([])
const modalRef = useTemplateRef('modalRef')

defineExpose({
  open: () => modalRef.value?.open(),
  close: () => modalRef.value?.close()
})

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>
