<template>
  <div class="h-full overflow-auto">
    <div class="relative p-4 flex flex-col">
      <div class="flex flex-wrap gap-2">
        <div class="w-full flex flex-col">
          <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 class="w-full flex gap-2 mt-2 pb-4 relative">
          <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 class="w-[calc(100%_+_32px)] absolute left-[-15px] bottom-0 h-px bg-cyan-200"></div>
        </div>
      </div>

      <button class="btn-cyan py-2 my-4" type="button" @click.prevent="addNewImage">New action</button>
      <Accordion v-for="action in spriteActions" :key="action.id">
        <template #header>
          <div class="flex justify-between items-center">
            {{ action.action }}
            <button class="btn-bordeaux px-4 py-1.5 min-w-24" type="button" @click.prevent="() => spriteActions.splice(spriteActions.indexOf(action), 1)">Remove</button>
          </div>
        </template>
        <template #content>
          <form class="flex gap-2.5 flex-wrap" @submit.prevent="saveSprite">
            <div class="form-field-full">
              <label for="action">Action</label>
              <input v-model="action.action" class="input-cyan" type="text" name="action" placeholder="Action" />
            </div>
            <div class="form-field-half">
              <label 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="form-field-half">
              <label 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="form-field-half">
              <label 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="form-field-half" v-if="action.isAnimated">
              <label 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="form-field-full" v-if="action.isAnimated">
              <label 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="form-field-full">
              <SpriteActionsInput v-model="action.sprites" />
            </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'
import { uuidv4 } from '@/utilities'

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

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

const spriteName = ref('')
const spriteActions = ref<SpriteAction[]>([])

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?.map((action) => {
        return {
          action: action.action,
          sprites: action.sprites,
          origin_x: action.origin_x,
          origin_y: action.origin_y,
          isAnimated: action.isAnimated,
          isLooping: action.isLooping,
          frameSpeed: action.frameSpeed,
          frameWidth: action.frameWidth,
          frameHeight: action.frameHeight
        }
      }) ?? []
  }

  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: uuidv4(), // Temporary ID, should be replaced by server-generated ID
    spriteId: selectedSprite.value.id,
    sprite: selectedSprite.value,
    action: 'new_action',
    sprites: [],
    origin_x: 0,
    origin_y: 0,
    isAnimated: false,
    isLooping: false,
    frameSpeed: 0,
    frameWidth: 0,
    frameHeight: 0
  }

  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>
