<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/25 rounded drop-shadow-20 py-1.5 px-4 inline-flex hover:bg-cyan hover:cursor-pointer">
      <input class="hidden" id="upload-asset" ref="spriteUploadField" type="file" accept="image/png" multiple @change="handleFileUpload" />
      Upload sprite(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-px bg-cyan-200"></div>
  </div>
  <a class="relative p-2.5 cursor-pointer" :class="{ 'bg-cyan/80': assetManagerStore.selectedSprite?.id === sprite.id }" v-for="(sprite, index) in filteredSprites" :key="index" @click="assetManagerStore.setSelectedSprite(sprite as Sprite)">
    <div class="flex items-center gap-2.5">
      <div class="h-7 w-16 max-w-16 flex justify-center">
        <img class="h-7" :src="`${config.server_endpoint}/assets/sprites/${sprite.id}.png`" alt="Sprite" />
      </div>
      <span>{{ sprite.name }}</span>
    </div>
    <div class="absolute left-0 bottom-0 w-full h-px 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 { Sprite } from '@/types'

const gameStore = useGameStore()
const spriteUploadField = 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:sprite:upload', files, (response: boolean) => {
    if (!response) {
      if (config.development) console.error('Failed to upload sprite')
      return
    }

    assetStore.fetchAssets()

    gameStore.connection?.emit('gm:sprite:list', {}, (response: Sprite[]) => {
      assetManagerStore.setSpriteList(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 filteredSprites = computed(() => {
  if (!searchQuery.value) {
    return assetManagerStore.spriteList
  }
  return assetManagerStore.spriteList.filter((sprite) => sprite.name.toLowerCase().includes(searchQuery.value.toLowerCase()))
})

onMounted(() => {
  gameStore.connection?.emit('gm:sprite:list', {}, (response: Sprite[]) => {
    assetManagerStore.setSpriteList(response)
  })
})
</script>
