<template>
  <div class="relative p-2.5 flex items-center gap-x-2.5">
    <input v-model="searchQuery" class="input-cyan flex-grow" placeholder="Search..." @input="handleSearch" />
    <button @click.prevent="newButtonClickHandler" class="bg-cyan/50 border border-solid border-white/25 rounded drop-shadow-20 p-2 inline-flex items-center justify-center hover:bg-cyan hover:cursor-pointer">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
      </svg>
    </button>
    <div class="absolute left-0 bottom-0 w-full h-px bg-cyan-200"></div>
  </div>
  <div v-bind="containerProps" class="overflow-y-auto relative" @scroll="onScroll">
    <div v-bind="wrapperProps" ref="elementToScroll">
      <a v-for="{ data: sprite } in list" :key="sprite.id" class="relative p-2.5 cursor-pointer block" :class="{ 'bg-cyan/80': assetManagerStore.selectedSprite?.id === sprite.id }" @click="assetManagerStore.setSelectedSprite(sprite as Sprite)">
        <div class="flex items-center gap-2.5">
          <span>{{ sprite.name }}</span>
        </div>
        <div class="absolute left-0 bottom-0 w-full h-px bg-cyan-200"></div>
      </a>
    </div>
    <button class="left-[calc(50%_-_60px)] fixed bottom-2.5 min-w-[unset] w-12 h-12 rounded-lg bg-cyan/50 p-0 hover:bg-cyan" v-show="hasScrolled" @click="toTop">
      <img class="absolute invert w-8 h-8 left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 rotate-180" src="/assets/icons/zoneEditor/chevron.svg" alt="" />
    </button>
  </div>
</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 { useVirtualList } from '@vueuse/core'
import type { Sprite } from '@/types'

const gameStore = useGameStore()
const assetManagerStore = useAssetManagerStore()
const assetStore = useAssetStore()

const searchQuery = ref('')

const hasScrolled = ref(false)
const elementToScroll = ref()

function newButtonClickHandler() {
  gameStore.connection?.emit('gm:sprite:create', {}, (response: boolean) => {
    if (!response) {
      if (config.development) console.error('Failed to create new sprite')
      return
    }

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

const handleSearch = () => {
  // Trigger a re-render of the virtual list
  virtualList.value?.scrollTo(0)
}

const filteredSprites = computed(() => {
  if (!searchQuery.value) {
    return assetManagerStore.spriteList
  }
  return assetManagerStore.spriteList.filter((sprite) => sprite.name.toLowerCase().includes(searchQuery.value.toLowerCase()))
})

const { list, containerProps, wrapperProps, scrollTo } = useVirtualList(filteredSprites, {
  itemHeight: 48
})

const virtualList = ref({ scrollTo })

const onScroll = () => {
  let scrollTop = elementToScroll.value.style.marginTop.replace('px', '')

  if (scrollTop > 80) {
    hasScrolled.value = true
  } else if (scrollTop <= 80) {
    hasScrolled.value = false
  }
}

function toTop() {
  virtualList.value?.scrollTo(0)
}

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