<template>
  <div class="asset add-new relative p-2.5 cursor-pointer flex gap-y-2.5 gap-x-5 flex-wrap">
    <label for="upload-asset" class="file-upload bg-cyan bg-opacity-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="tileUploadField" type="file" accept="image/png" multiple @change="handleFileUpload" />
      Upload tile(s)
    </label>
    <input v-model="searchQuery" class="input-cyan search-field w-full" placeholder="Search..." @input="handleSearch" />
    <div class="absolute left-0 bottom-0 w-full height-[1px] bg-cyan-200"></div>
  </div>
  <a class="asset relative p-2.5 cursor-pointer flex gap-y-2.5 gap-x-5 flex-wrap" :class="{ active: assetManagerStore.selectedTile === tile }" v-for="(tile, index) in filteredTiles" :key="index" @click="assetManagerStore.setSelectedTile(tile)">
    <div class="asset-details flex items-center gap-2.5">
      <!--      TODO make all img have same width so text aligns nicely -->
      <img class="h-[28px]" :src="`${config.server_endpoint}/assets/tiles/${tile}.png`" alt="Tile" />
      <span class="asset-name flex-shrink-0">{{ tile }}</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 { useSocketStore } from '@/stores/socket'
import { onMounted, ref, computed } from 'vue'
import { useAssetManagerStore } from '@/stores/assetManager'
import { useAssetStore } from '@/stores/assets'

const socket = useSocketStore()
const tileUploadField = 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
  socket.connection.emit('gm:tile:upload', files, (response: boolean) => {
    if (!response) {
      if (config.development) console.error('Failed to upload tile')
      return
    }

    assetStore.fetchAssets()

    socket.connection.emit('gm:tile:list', {}, (response: string[]) => {
      assetManagerStore.setTileList(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 filteredTiles = computed(() => {
  if (!searchQuery.value) {
    return assetManagerStore.tileList
  }
  return assetManagerStore.tileList.filter(tile =>
    tile.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

onMounted(() => {
  socket.connection.emit('gm:tile:list', {}, (response: string[]) => {
    if (config.development) console.log(response)
    assetManagerStore.setTileList(response)
  })
})
</script>