<template>
  <div class="absolute border-0 border-l-2 border-solid border-gray-500 w-1/4 min-w-80 flex flex-col top-0 right-0 z-10 h-dvh bg-gray-800" v-if="mapEditor.tool.value === 'pencil' && mapEditor.drawMode.value === 'map_object'">
    <div class="flex flex-col gap-2.5 p-2.5">
      <div class="relative flex">
        <img src="/assets/icons/mapEditor/search.svg" class="w-4 h-4 py-0.5 absolute top-1/2 -translate-y-1/2 left-2.5" alt="Search icon" />
        <label class="mb-1.5 font-titles hidden" for="search">Search</label>
        <input @mousedown.stop class="!pl-7 input-field w-full" type="text" name="search" placeholder="Search" v-model="searchQuery" />
      </div>
      <div class="flex">
        <select class="input-field w-full" name="lists" v-model="mapEditor.drawMode.value" @change="(event: any) => mapEditor.setDrawMode(event.target.value)">
          <option value="tile">Tiles</option>
          <option value="map_object">Objects</option>
        </select>
      </div>
    </div>
    <div class="h-full overflow-auto relative border-0 border-t border-solid border-gray-500 p-2.5">
      <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>
    </div>
    <div class="flex flex-col h-40 gap-2.5 p-3.5 border-t border-0 border-solid border-gray-500">
      <span>Tags:</span>
      <div class="flex grow items-center flex-wrap gap-1.5 overflow-auto">
        <span class="m-auto">No tags selected</span>
      </div>
    </div>
  </div>
</template>

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

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

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

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

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
  })
})

let subscription: any = null

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

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