<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="isOpen">
    <div class="relative z-10 p-2.5 border-solid border-0 border-b border-gray-500">
      <h3 class="text-lg text-white">Map objects</h3>
    </div>
    <div class="overflow-hidden grow relative">
      <div class="absolute w-full h-full top-0 left-0">
        <div class="relative z-10 h-full">
          <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-[calc(100%_-_170px)] p-4 pb-24">
            <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 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>
      </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>
