<template>
  <div class="relative p-2.5 cursor-pointer flex gap-y-2.5 gap-x-5 flex-wrap">
    <label for="upload-asset" class="bg-cyan/50 border border-solid border-white rounded drop-shadow-20 py-1.5 px-[15px] inline-flex hover:bg-cyan hover:cursor-pointer">
      <input class="hidden" id="upload-asset" ref="objectUploadField" type="file" accept="image/png" multiple @change="handleFileUpload" />
      Upload object(s)
    </label>
    <input v-model="searchQuery" class="input-cyan w-full" placeholder="Search..." @input="handleSearch" />
    <div class="absolute left-0 bottom-0 w-full h-[1px] bg-cyan-200"></div>
  </div>
  <a class="relative p-2.5 cursor-pointer" :class="{ 'bg-cyan/80': assetManagerStore.selectedObject?.id === object.id }" v-for="(object, index) in filteredObjects" :key="index" @click="assetManagerStore.setSelectedObject(object as Object)">
    <div class="flex items-center gap-2.5">
      <div class="h-[28px] w-[75px] max-w-[75px] flex justify-center">
        <img class="h-[28px]" :src="`${config.server_endpoint}/assets/objects/${object.id}.png`" alt="Object" />
      </div>
      <span>{{ object.name }}</span>
    </div>
    <div class="absolute left-0 bottom-0 w-full h-[1px] bg-cyan-200"></div>
  </a>
</template>

<script setup lang="ts">
import config from '@/config'
import { useGameStore } from '@/stores/game'
import { onMounted, ref, computed } from 'vue'
import { useAssetManagerStore } from '@/stores/assetManager'
import { useAssetStore } from '@/stores/assets'
import type { Object } from '@/types'

const gameStore = useGameStore()
const objectUploadField = ref(null)
const assetManagerStore = useAssetManagerStore()
const assetStore = useAssetStore()

const searchQuery = ref('')

const handleFileUpload = (e: Event) => {
  const files = (e.target as HTMLInputElement).files
  if (!files) return
  gameStore.connection.emit('gm:object:upload', files, (response: boolean) => {
    if (!response) {
      if (config.development) console.error('Failed to upload object')
      return
    }

    assetStore.fetchAssets()

    gameStore.connection.emit('gm:object:list', {}, (response: Object[]) => {
      assetManagerStore.setObjectList(response)
    })
  })
}

const handleSearch = () => {
  // The filtering is handled by the computed property, so we don't need to do anything here
  // This function is kept in case you want to add debounce or other functionality later
}

const filteredObjects = computed(() => {
  if (!searchQuery.value) {
    return assetManagerStore.objectList
  }
  return assetManagerStore.objectList.filter((object) => object.name.toLowerCase().includes(searchQuery.value.toLowerCase()))
})

onMounted(() => {
  gameStore.connection.emit('gm:object:list', {}, (response: Object[]) => {
    assetManagerStore.setObjectList(response)
  })
})
</script>
