<template>
  <div class="tile-manager h-full overflow-auto">
    <div class="image-container relative p-2.5 flex items-center justify-center h-[300px]">
      <img class="max-h-[280px]" :src="tileImageUrl" :alt="'Tile ' + selectedTile" />
      <div class="absolute left-0 bottom-0 w-full h-[1px] bg-cyan-200"></div>
    </div>
    <div class="modal-form asset-manager m-2.5 p-2.5 block">
      <form class="flex g-2.5 flex-wrap" @submit.prevent>
        <div class="flex flex-col mb-5">
          <label class="mb-1.5 font-titles" for="tags">Tags</label>
          <ChipsInput v-model="tags" @update:modelValue="handleTagsUpdate" />
        </div>
        <div class="w-full">
          <button class="btn-bordeaux px-[15px] py-1.5 min-w-[100px]" type="button" @click="removeTile">Remove</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onBeforeUnmount, onMounted } from 'vue'
import { useAssetManagerStore } from '@/stores/assetManager'
import { useSocketStore } from '@/stores/socket'
import ChipsInput from '@/components/forms/ChipsInput.vue'
import config from '@/config'

const socket = useSocketStore()
const assetManagerStore = useAssetManagerStore()

const tags = ref<string[]>([])

const selectedTile = computed(() => assetManagerStore.selectedTile)

const tileImageUrl = computed(() => `${config.server_endpoint}/assets/tiles/${selectedTile.value}.png`)

watch(selectedTile, fetchTileTags)

function fetchTileTags(tile: string) {
  if (config.development) console.log('P241 selectedTile', tile)
  socket.connection.emit('gm:tile:tags', { tile }, (response: string[]) => {
    tags.value = response
  })
}

function handleTagsUpdate(newTags: string[]) {
  if (config.development) console.log(newTags)
  saveTags(newTags)
}

function saveTags(tagsToSave: string[]) {
  socket.connection.emit(
    'gm:tile:tags:update',
    {
      tile: selectedTile.value,
      tags: tagsToSave
    },
    (response: boolean) => {
      if (!response) console.error('Failed to save tags')
    }
  )
}

function removeTile() {
  socket.connection.emit('gm:tile:remove', { tile: selectedTile.value }, (response: boolean) => {
    if (!response) {
      console.error('Failed to remove tile')
      return
    }
    refreshTileList()
  })
}

function refreshTileList() {
  socket.connection.emit('gm:tile:list', {}, (response: string[]) => {
    assetManagerStore.setTileList(response)
    assetManagerStore.setSelectedTile('')
  })
}

onMounted(() => {
  if (!selectedTile.value) return
  fetchTileTags(selectedTile.value)
})

onBeforeUnmount(() => {
  assetManagerStore.setSelectedTile('')
})
</script>
