<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="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="lists">
          <option value="tiles">Tiles</option>
          <option value="objects">Objects</option>
        </select>
      </div>
    </div>
    <div class="h-full overflow-auto relative border-0 border-t border-solid border-gray-500 p-2.5">
      <TileList v-if="lists === 'tiles'" />
      <ObjectList v-if="lists === 'objects'" />
    </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 { Tile } from '@/application/types'
import { TileStorage } from '@/storage/storages'
import { liveQuery } from 'dexie'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import TileList from '@/components/gameMaster/mapEditor/partials/lists/TileList.vue'
import ObjectList from '@/components/gameMaster/mapEditor/partials/lists/MapObjectList.vue'

const isOpen = ref(false)
const tileStorage = new TileStorage()
const searchQuery = ref('')
const tiles = ref<Tile[]>([])
const lists = ref<'tiles' | 'objects'>('tiles')

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

let subscription: any = null

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

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