<template>
  <div class="h-full overflow-auto">
    <div class="relative p-4 flex flex-col">
      <div class="gap-2.5 flex flex-wrap">
        <div class="w-full flex flex-col mb-1">
          <label class="mb-1.5 font-titles" for="name">Name</label>
          <input v-model="spriteName" class="input-cyan" type="text" name="name" placeholder="New sprite" />
        </div>
      </div>
      <div class="flex gap-2 py-2">
        <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 class="w-full mb-2 h-px bg-cyan-200"></div>
      <button class="btn-cyan px-4 py-1.5 flex-1 sm:flex-none sm:min-w-24 mb-4" type="button" @click.prevent="addNewImage">New action</button>
      <Accordion v-for="action in spriteActions" :key="action.id">
        <template #header>
          <div class="flex items-center">
            {{ action.action }}
            <div class="ml-auto flex gap-2">
              <button class="btn-bordeaux px-4 py-1.5 flex-1 sm:flex-none sm:min-w-24" type="button" @click.prevent="() => spriteActions.splice(spriteActions.indexOf(action), 1)">Remove</button>
            </div>
          </div>
        </template>
        <template #content>
          <form class="flex gap-2.5 flex-wrap" @submit.prevent="saveSprite">
            <div class="w-full flex flex-col mb-5">
              <label class="mb-1.5 font-titles" for="action">Action</label>
              <input v-model="action.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="action.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="action.origin_y" class="input-cyan" type="number" step="any" name="origin-y" placeholder="Origin Y" />
            </div>
            <div class="w-[calc(50%_-_5px)] flex flex-col mb-5">
              <label class="mb-1.5 font-titles" for="is-animated">Is animated</label>
              <select v-model="action.isAnimated" class="input-cyan" name="is-animated">
                <option :value="false">No</option>
                <option :value="true">Yes</option>
              </select>
            </div>
            <div class="w-[calc(50%_-_5px)] flex flex-col mb-5">
              <label class="mb-1.5 font-titles" for="is-looping">Is looping</label>
              <select v-model="action.isLooping" class="input-cyan" name="is-looping">
                <option :value="false">No</option>
                <option :value="true">Yes</option>
              </select>
            </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="action.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="action.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="action.frameHeight" class="input-cyan" type="number" step="any" name="frame-height" placeholder="Frame height" />
            </div>
            <div class="w-full flex mb-5 gap-2">
              <SpriteActionsInput v-model="action.spriteActions" />
            </div>
            <div v-if="action.base64">
              <div class="w-full h-px bg-cyan-200"></div>
              <img class="max-h-56" :src="`data:image/png;base64,${action.base64}`" />
            </div>
          </form>
        </template>
      </Accordion>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Sprite, spriteAction } 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'
import SpriteActionsInput from '@/components/utilities/assetManager/partials/sprite/partials/SpriteImagesInput.vue'

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

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

const spriteName = ref('')

type uploadSpriteAction = spriteAction & {
  base64?: string
}

const spriteActions = ref<uploadSpriteAction[]>([])

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

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

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,
    spriteActions: spriteActions.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: spriteAction = {
    id: Date.now().toString(), // Temporary ID, should be replaced by server-generated ID
    action: 'new_action',
    origin_x: 0,
    origin_y: 0,
    frameSpeed: 0,
    frameWidth: 0,
    frameHeight: 0,
    isAnimated: false,
    spriteId: selectedSprite.value.id,
    sprite: selectedSprite.value,
    isLooping: false
  }

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

  spriteActions.value.push(newImage)
}

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

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

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