<template>
  <div class="h-full overflow-auto">
    <div class="relative p-2.5 flex flex-col items-center justify-between">
      <div class="w-full flex flex-col sm:flex-row items-center gap-9 mb-5">
        <div class="w-full sm:flex-grow">
          <input v-model="spriteName" class="input-cyan w-full" type="text" name="name" placeholder="New sprite" />
        </div>
        <div class="flex gap-2 w-full sm:w-auto">
          <button class="btn-cyan px-4 py-2 flex-1 sm:flex-none sm:min-w-24" type="button" @click.prevent="saveSprite">Save</button>
          <button class="btn-bordeaux px-4 py-2 flex-1 sm:flex-none sm:min-w-24" type="button" @click.prevent="removeSprite">Remove</button>
        </div>
      </div>
      <div class="w-full h-px bg-cyan-200"></div>
    </div>
    <div class="m-2.5 px-2.5 block">
      <button class="btn-cyan px-4 py-1.5 flex-1 sm:flex-none sm:min-w-24 mb-5" type="button" @click.prevent="addNewImage">New IMG</button>
      <Accordion v-for="image in spriteImages" :key="image.id">
        <template #header>
          <div class="flex items-center">
            {{ image.name }}
            <div class="ml-auto flex gap-2">
              <label for="upload-asset" class="text-sm bg-cyan/50 border border-solid border-white/25 rounded drop-shadow-20 px-4 py-1.5 inline-flex items-center justify-center hover:bg-cyan hover:cursor-pointer">
                <input class="hidden" id="upload-asset" type="file" accept="image/png" @change="(event) => handleImageUpload(event, image)" />
                Set image
              </label>
              <button class="btn-bordeaux px-4 py-1.5 flex-1 sm:flex-none sm:min-w-24" type="button" @click.prevent="() => spriteImages.splice(spriteImages.indexOf(image), 1)">Remove</button>
            </div>
          </div>
        </template>
        <template #content>
          <form class="flex gap-2.5 flex-wrap" @submit.prevent="saveSprite">
            <div class="w-[calc(50%_-_5px)] flex flex-col mb-5">
              <label class="mb-1.5 font-titles" for="name">Name</label>
              <input v-model="image.name" class="input-cyan" type="text" name="name" placeholder="Wall #1" />
            </div>
            <div class="w-[calc(50%_-_5px)] flex flex-col mb-5">
              <label class="mb-1.5 font-titles" for="action">Action</label>
              <input v-model="image.action" class="input-cyan" type="text" name="action" placeholder="Action" />
            </div>
            <div class="w-[calc(50%_-_5px)] flex flex-col mb-5">
              <label class="mb-1.5 font-titles" for="origin-x">Origin X</label>
              <input v-model.number="image.origin_x" class="input-cyan" type="number" step="any" name="origin-x" placeholder="Origin X" />
            </div>
            <div class="w-[calc(50%_-_5px)] flex flex-col mb-5">
              <label class="mb-1.5 font-titles" for="origin-y">Origin Y</label>
              <input v-model.number="image.origin_y" class="input-cyan" type="number" step="any" name="origin-y" placeholder="Origin Y" />
            </div>
            <div class="w-full flex flex-col mb-5">
              <label class="mb-1.5 font-titles" for="frame-speed">Frame speed</label>
              <input v-model.number="image.frameSpeed" class="input-cyan" type="number" step="any" name="frame-speed" placeholder="Frame speed" />
            </div>
            <div class="w-[calc(50%_-_5px)] flex flex-col mb-5">
              <label class="mb-1.5 font-titles" for="frame-width">Frame width</label>
              <input v-model.number="image.frameWidth" class="input-cyan" type="number" step="any" name="frame-width" placeholder="Frame width" />
            </div>
            <div class="w-[calc(50%_-_5px)] flex flex-col mb-5">
              <label class="mb-1.5 font-titles" for="frame-height">Frame height</label>
              <input v-model.number="image.frameHeight" class="input-cyan" type="number" step="any" name="frame-height" placeholder="Frame height" />
            </div>
            <div class="w-full flex flex-col mb-5">
              <label class="mb-1.5 font-titles" for="is-looping">Is looping</label>
              <select v-model="image.isLooping" class="input-cyan" name="is-looping">
                <option :value="false">No</option>
                <option :value="true">Yes</option>
              </select>
            </div>
            <div v-if="image.base64">
              <div class="w-full h-px bg-cyan-200"></div>
              <img class="max-h-56" :src="`data:image/png;base64,${image.base64}`" />
            </div>
          </form>
        </template>
      </Accordion>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Sprite, SpriteImage } from '@/types'
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useAssetManagerStore } from '@/stores/assetManager'
import { useGameStore } from '@/stores/game'
import Accordion from '@/components/utilities/Accordion.vue'

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

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

const spriteName = ref('')

type uploadSpriteImage = SpriteImage & {
  base64?: string
}

const spriteImages = ref<uploadSpriteImage[]>([])

if (!selectedSprite.value) {
  console.error('No sprite selected')
}

if (selectedSprite.value) {
  spriteName.value = selectedSprite.value.name
  spriteImages.value = selectedSprite.value.spriteImages
}

function handleImageUpload(event: Event, image: uploadSpriteImage) {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (!file) return

  const reader = new FileReader()
  reader.onload = (e) => {
    const base64String = e.target?.result as string
    image.base64 = base64String.split(',')[1] // Remove the data:image/png;base64, prefix
  }
  reader.readAsDataURL(file)
}

function removeSprite() {
  gameStore.connection?.emit('gm:sprite:remove', { id: selectedSprite.value?.id }, (response: boolean) => {
    if (!response) {
      console.error('Failed to remove sprite')
      return
    }
    refreshSpriteList()
  })
}

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

    if (unsetSelectedSprite) {
      assetManagerStore.setSelectedSprite(null)
    }
  })
}

function saveSprite() {
  if (!selectedSprite.value) {
    console.error('No sprite selected')
    return
  }

  const updatedSprite = {
    id: selectedSprite.value.id,
    name: spriteName.value,
    spriteImages: spriteImages.value
  }

  gameStore.connection?.emit('gm:sprite:update', updatedSprite, (response: boolean) => {
    if (!response) {
      console.error('Failed to save sprite')
      return
    }
    refreshSpriteList(false)
  })
}

function addNewImage() {
  if (!selectedSprite.value) return

  const newImage: SpriteImage = {
    id: Date.now().toString(), // Temporary ID, should be replaced by server-generated ID
    name: 'New image',
    origin_x: 0,
    origin_y: 0,
    frameSpeed: 0,
    frameWidth: 0,
    frameHeight: 0,
    isAnimated: false,
    spriteId: selectedSprite.value.id,
    sprite: selectedSprite.value,
    action: '',
    isLooping: false
  }

  // spriteimages value can be undefined
  if (!spriteImages.value) {
    spriteImages.value = []
  }

  spriteImages.value.push(newImage)
}

watch(selectedSprite, (sprite: Sprite | null) => {
  if (!sprite) return
  spriteName.value = sprite.name
  spriteImages.value = sprite.spriteImages
})

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

onBeforeUnmount(() => {
  assetManagerStore.setSelectedSprite(null)
})
</script>
