<template>
  <div class="h-full overflow-auto">
    <div class="relative p-2.5 flex flex-col items-center justify-center h-72 rounded-md default-border bg-gray">
      <div class="grid grid-cols-[160px_auto_max-content] gap-12">
        <div>
          <input type="checkbox" checked v-model="showOrigin" /><label>Show Origin</label>
          <br />
          <input type="checkbox" checked v-model="showPartitionOverlay" /><label>Show Partitions</label>
        </div>
        <div class="relative w-fit h-fit">
          <img class="max-h-56" :src="`${config.server_endpoint}/textures/map_objects/${selectedMapObject?.id}.png`" :alt="'Object ' + selectedMapObject?.id" ref="imageRef" />
          <svg ref="svg" class="absolute top-0 left-0 w-full h-full inline-block pointer-events-none">
            <circle v-if="showOrigin && svg" r="4" :cx="mapObjectOriginX * width" :cy="mapObjectOriginY * height" stroke="white" stroke-width="2" />
            <rect v-if="showPartitionOverlay && svg" v-for="(offset, index) in mapObjectDepthOffsets" style="opacity: 0.5" stroke="red" :x="index * (width / mapObjectDepthOffsets.length)" :width="width / mapObjectDepthOffsets.length" :y="0" :height="height" />
          </svg>
        </div>
        <div>
          <button class="btn-cyan px-4 py-1.5 min-w-24" @click="mapObjectDepthOffsets.push(0)">Add Partition</button>
          <p>Depth Offset</p>
          <div class="text-white grid grid-cols-[120px_80px_auto] items-baseline gap-2" v-for="(offset, index) in mapObjectDepthOffsets">
            <input class="input-field max-h-4 mt-2" type="number" :value="offset" @change="setPartitionDepth($event, index)" />
            <button @click="mapObjectDepthOffsets.splice(index, 1)">Remove</button>
          </div>
        </div>
      </div>
    </div>

    <div class="mt-5 block">
      <form class="flex gap-2.5 flex-wrap" @submit.prevent="saveObject">
        <div class="form-field-full">
          <label for="name">Name</label>
          <input v-model="mapObjectName" class="input-field" type="text" name="name" placeholder="Wall #1" />
        </div>
        <div class="form-field-half">
          <label for="origin-x">Origin X</label>
          <input v-model="mapObjectOriginX" class="input-field" 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="mapObjectOriginY" class="input-field" type="number" step="any" name="origin-y" placeholder="Origin Y" />
        </div>
        <div class="form-field-full">
          <label for="tags">Tags</label>
          <ChipsInput v-model="mapObjectTags" @update:modelValue="mapObjectTags = $event" />
        </div>
        <div class="form-field-full">
          <label for="frame-speed">Frame rate</label>
          <input v-model="mapObjectFrameRate" class="input-field" type="number" step="any" name="frame-speed" placeholder="Frame rate" />
        </div>
        <div class="form-field-half">
          <label for="frame-width">Frame width</label>
          <input v-model="mapObjectFrameWidth" class="input-field" type="number" step="any" name="frame-width" placeholder="Frame width" />
        </div>
        <div class="form-field-half">
          <label for="frame-height">Frame height</label>
          <input v-model="mapObjectFrameHeight" class="input-field" type="number" step="any" name="frame-height" placeholder="Frame height" />
        </div>
        <div class="flex gap-4">
          <button class="btn-cyan px-4 py-1.5 min-w-24" type="submit">Save</button>
          <button class="btn-red px-4 py-1.5 min-w-24" type="button" @click.prevent="removeObject">Delete</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import config from '@/application/config'
import { SocketEvent } from '@/application/enums'
import type { MapObject } from '@/application/types'
import { downloadCache } from '@/application/utilities'
import ChipsInput from '@/components/forms/ChipsInput.vue'
import { socketManager } from '@/managers/SocketManager'
import { MapObjectStorage } from '@/storage/storages'
import { useAssetManagerStore } from '@/stores/assetManagerStore'
import { useElementSize } from '@vueuse/core'
import { Rectangle } from 'phavuer'
import { computed, onBeforeUnmount, onMounted, ref, useTemplateRef, watch } from 'vue'

const assetManagerStore = useAssetManagerStore()

const selectedMapObject = computed(() => assetManagerStore.selectedMapObject)
const svg = useTemplateRef('svg')
const { width, height } = useElementSize(svg)

const mapObjectName = ref('')
const mapObjectTags = ref<string[]>([])
const mapObjectDepthOffsets = ref<number[]>([])
const mapObjectOriginX = ref(0)
const mapObjectOriginY = ref(0)
const mapObjectFrameRate = ref(0)
const mapObjectFrameWidth = ref(0)
const mapObjectFrameHeight = ref(0)
const imageRef = ref<HTMLImageElement | null>(null)
const showOrigin = ref(true)
const showPartitionOverlay = ref(true)

if (!selectedMapObject.value) {
  console.error('No map mapObject selected')
}

if (selectedMapObject.value) {
  mapObjectName.value = selectedMapObject.value.name
  mapObjectTags.value = selectedMapObject.value.tags
  mapObjectDepthOffsets.value = selectedMapObject.value.depthOffsets
  mapObjectOriginX.value = selectedMapObject.value.originX
  mapObjectOriginY.value = selectedMapObject.value.originY
  mapObjectFrameRate.value = selectedMapObject.value.frameRate
  mapObjectFrameWidth.value = selectedMapObject.value.frameWidth
  mapObjectFrameHeight.value = selectedMapObject.value.frameHeight
}

const setPartitionDepth = (event: any, idx: number) => (mapObjectDepthOffsets.value[idx] = Number.parseInt(event.target.value))

async function removeObject() {
  if (!selectedMapObject.value) return
  socketManager.emit(SocketEvent.GM_MAPOBJECT_REMOVE, { mapObjectId: selectedMapObject.value.id }, async (response: boolean) => {
    if (!response) {
      console.error('Failed to remove mapObject')
      return
    }

    await downloadCache('map_objects', new MapObjectStorage())
    await refreshObjectList()
  })
}

async function refreshObjectList(unsetSelectedMapObject = true) {
  socketManager.emit(SocketEvent.GM_MAPOBJECT_LIST, {}, (response: MapObject[]) => {
    assetManagerStore.setMapObjectList(response)

    if (unsetSelectedMapObject) {
      assetManagerStore.setSelectedMapObject(null)
    }
  })
}

async function saveObject() {
  if (!selectedMapObject.value) {
    console.error('No mapObject selected')
    return
  }
  socketManager.emit(
    SocketEvent.GM_MAPOBJECT_UPDATE,
    {
      id: selectedMapObject.value.id,
      name: mapObjectName.value,
      tags: mapObjectTags.value,
      depthOffsets: mapObjectDepthOffsets.value,
      originX: mapObjectOriginX.value,
      originY: mapObjectOriginY.value,
      frameRate: mapObjectFrameRate.value,
      frameWidth: mapObjectFrameWidth.value,
      frameHeight: mapObjectFrameHeight.value
    },
    async (response: boolean) => {
      if (!response) {
        console.error('Failed to save mapObject')
        return
      }

      await downloadCache('map_objects', new MapObjectStorage())
      await refreshObjectList(false)
    }
  )
}

watch(selectedMapObject, (mapObject: MapObject | null) => {
  if (!mapObject) return
  mapObjectName.value = mapObject.name
  mapObjectTags.value = mapObject.tags
  mapObjectDepthOffsets.value = mapObject.depthOffsets
  mapObjectOriginX.value = mapObject.originX
  mapObjectOriginY.value = mapObject.originY
  mapObjectFrameRate.value = mapObject.frameRate
  mapObjectFrameWidth.value = mapObject.frameWidth
  mapObjectFrameHeight.value = mapObject.frameHeight
})

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

// function startDragging(index: number, event: MouseEvent) {
//   isDragging.value = true
//   draggedPointIndex.value = index
//
//   const moveHandler = (e: MouseEvent) => {
//     if (!isDragging.value || !imageRef.value) return
//     const rect = imageRef.value.getBoundingClientRect()
//     mapObjectPivotPoints.value[draggedPointIndex.value] = {
//       x: e.clientX - rect.left,
//       y: e.clientY - rect.top
//     }
//   }
//
//   const upHandler = () => {
//     isDragging.value = false
//     draggedPointIndex.value = -1
//     window.removeEventListener('mousemove', moveHandler)
//     window.removeEventListener('mouseup', upHandler)
//   }
//
//   window.addEventListener('mousemove', moveHandler)
//   window.addEventListener('mouseup', upHandler)
// }

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

<style scoped>
.pointer-events-none {
  pointer-events: none;
}
</style>
