<template>
  <TilemapLayerC :tilemap="zoneTilemap" :tileset="tileArray" :layerIndex="0" :cull-padding="10" />
  <Controls :layer="tiles" />

  <Container :depth="2">
    <Image v-for="object in sortedZoneObjects" :key="object.id" v-bind="getObjectImageProps(object)" @pointerup="() => zoneEditorStore.setSelectedZoneObject(object)" />
  </Container>

  <Container :depth="3">
    <Image v-for="tile in zoneEventTiles" :key="tile.id" v-bind="getEventTileImageProps(tile)" />
  </Container>

  <Toolbar :layer="tiles" @eraser="eraser" @pencil="pencil" @paint="paint" @clear="clear" @save="save" />
  <SelectedZoneObject v-if="zoneEditorStore.selectedZoneObject" @update_depth="updateZoneObjectDepth" @delete="deleteZoneObject" @move="handleMove" />
  <Tiles v-if="zoneEditorStore.isTileListModalShown" />
  <Objects v-if="zoneEditorStore.isObjectListModalShown" />
  <ZoneSettings v-if="zoneEditorStore.isSettingsModalShown" />
  <ZoneList v-if="zoneEditorStore.isZoneListModalShown" />
  <TeleportModal v-if="shouldShowTeleportModal" />
</template>

<script setup lang="ts">
import { computed, onBeforeMount, onBeforeUnmount, ref } from 'vue'
import { Container, Image, TilemapLayer as TilemapLayerC, useScene } from 'phavuer'
import { storeToRefs } from 'pinia'
import { useGameStore } from '@/stores/game'
import { useZoneEditorStore } from '@/stores/zoneEditor'
import { useAssetStore } from '@/stores/assets'
import { placeTile, setAllTiles, sortByDepth, tileToWorldX, tileToWorldY } from '@/services/zone'
import { ZoneEventTileType, type ZoneObject, type ZoneEventTile } from '@/types'
import { uuidv4 } from '@/utilities'
import config from '@/config'

// Components
import Controls from '@/components/utilities/Controls.vue'
import Toolbar from '@/components/utilities/zoneEditor/partials/Toolbar.vue'
import Tiles from '@/components/utilities/zoneEditor/partials/TileList.vue'
import SelectedZoneObject from '@/components/utilities/zoneEditor/partials/SelectedZoneObject.vue'
import ZoneSettings from '@/components/utilities/zoneEditor/partials/ZoneSettings.vue'
import Objects from '@/components/utilities/zoneEditor/partials/ObjectList.vue'
import ZoneList from '@/components/utilities/zoneEditor/partials/ZoneList.vue'
import TeleportModal from '@/components/utilities/zoneEditor/partials/TeleportModal.vue'

const scene = useScene()
const gameStore = useGameStore()
const zoneEditorStore = useZoneEditorStore()
const assetStore = useAssetStore()

const { objectList, zone, selectedTile, selectedObject, selectedZoneObject, eraserMode, drawMode, objectDepth } = storeToRefs(zoneEditorStore)

const zoneTilemap = ref(createTilemap())
const tiles = ref(createTileLayer())
const zoneObjects = ref<ZoneObject[]>([])
const zoneEventTiles = ref<ZoneEventTile[]>([])
const tileArray = ref(createTileArray())

const sortedZoneObjects = computed(() => sortByDepth(zoneObjects.value, zoneTilemap.value.width))
const shouldShowTeleportModal = computed(() => zoneEditorStore.tool === 'pencil' && drawMode.value === 'teleport')

function createTilemap() {
  const zoneData = new Phaser.Tilemaps.MapData({
    width: zone.value?.width ?? 10,
    height: zone.value?.height ?? 10,
    tileWidth: config.tile_size.x,
    tileHeight: config.tile_size.y,
    orientation: Phaser.Tilemaps.Orientation.ISOMETRIC,
    format: Phaser.Tilemaps.Formats.ARRAY_2D
  })
  return new Phaser.Tilemaps.Tilemap(scene, zoneData)
}

function createTileLayer() {
  const tilesetImages = assetStore.assets.filter((asset) => asset.group === 'tiles').map((asset, index) => zoneTilemap.value.addTilesetImage(asset.key, asset.key, config.tile_size.x, config.tile_size.y, 0, 0, index + 1))
  tilesetImages.push(zoneTilemap.value.addTilesetImage('blank_tile', 'blank_tile', config.tile_size.x, config.tile_size.y, 0, 0, 0))
  return zoneTilemap.value.createBlankLayer('tiles', tilesetImages, 0, config.tile_size.y)
}

function createTileArray() {
  return Array.from({ length: zone.value?.width ?? 0 }, () => Array.from({ length: zone.value?.height ?? 0 }, () => 'blank_tile'))
}

function getObjectImageProps(object: ZoneObject) {
  return {
    tint: selectedZoneObject.value?.id === object.id ? 0x00ff00 : 0xffffff,
    x: tileToWorldX(zoneTilemap.value, object.positionX, object.positionY),
    y: tileToWorldY(zoneTilemap.value, object.positionX, object.positionY),
    texture: object.object.id,
    originY: Number(object.object.originX),
    originX: Number(object.object.originY)
  }
}

function getEventTileImageProps(tile: ZoneEventTile) {
  return {
    x: tileToWorldX(zoneTilemap.value, tile.positionX, tile.positionY),
    y: tileToWorldY(zoneTilemap.value, tile.positionX, tile.positionY),
    texture: tile.type
  }
}

function eraser(tile: Phaser.Tilemaps.Tile) {
  if (eraserMode.value === 'tile') {
    placeTile(zoneTilemap.value, tiles.value, tile.x, tile.y, 'blank_tile')
    tileArray.value[tile.y][tile.x] = 'blank_tile'
  } else if (eraserMode.value === 'object') {
    zoneObjects.value = zoneObjects.value.filter((object) => object.positionX !== tile.x || object.positionY !== tile.y)
  } else if (eraserMode.value === 'blocking tile' || eraserMode.value === 'teleport') {
    zoneEventTiles.value = zoneEventTiles.value.filter((eventTile) => eventTile.positionX !== tile.x || eventTile.positionY !== tile.y || (eraserMode.value === 'teleport' && eventTile.type !== ZoneEventTileType.TELEPORT))
  }
}

function pencil(tile: Phaser.Tilemaps.Tile) {
  if (drawMode.value === 'tile' && selectedTile.value) {
    placeTile(zoneTilemap.value, tiles.value, tile.x, tile.y, selectedTile.value.id)
    tileArray.value[tile.y][tile.x] = selectedTile.value.id
  } else if (drawMode.value === 'object' && selectedObject.value) {
    addZoneObject(tile)
  } else if (drawMode.value === 'blocking tile' || drawMode.value === 'teleport') {
    addZoneEventTile(tile)
  }
}

function addZoneObject(tile: Phaser.Tilemaps.Tile) {
  const newObject = {
    id: uuidv4(),
    zoneId: zone.value!.id,
    zone: zone.value!,
    objectId: selectedObject.value!.id,
    object: selectedObject.value!,
    depth: objectDepth.value,
    positionX: tile.x,
    positionY: tile.y
  }
  zoneObjects.value = [...new Set([...zoneObjects.value, newObject])]
}

function addZoneEventTile(tile: Phaser.Tilemaps.Tile) {
  const newEventTile = {
    id: uuidv4(),
    zoneId: zone.value!.id,
    zone: zone.value!,
    type: drawMode.value === 'blocking tile' ? ZoneEventTileType.BLOCK : ZoneEventTileType.TELEPORT,
    positionX: tile.x,
    positionY: tile.y,
    teleport:
      drawMode.value === 'teleport'
        ? {
            toZoneId: zoneEditorStore.teleportSettings.toZoneId,
            toPositionX: zoneEditorStore.teleportSettings.toPositionX,
            toPositionY: zoneEditorStore.teleportSettings.toPositionY
          }
        : undefined
  }
  zoneEventTiles.value = [...new Set([...zoneEventTiles.value, newEventTile])]
}

function paint() {
  if (!selectedTile.value) return
  tileArray.value.forEach((row, y) =>
    row.forEach((_, x) => {
      placeTile(zoneTilemap.value, tiles.value, x, y, selectedTile.value!.id)
      tileArray.value[y][x] = selectedTile.value!.id
    })
  )
}

function save() {
  if (!zone.value) return
  console.log('update')
  const data = {
    zoneId: zone.value.id,
    name: zone.value.name,
    width: zone.value.width,
    height: zone.value.height,
    tiles: tileArray.value,
    pvp: zone.value.pvp,
    zoneEventTiles: zoneEventTiles.value.map(({ id, zoneId, type, positionX, positionY, teleport }) => ({ id, zoneId, type, positionX, positionY, teleport })),
    zoneObjects: zoneObjects.value.map(({ id, zoneId, objectId, depth, positionX, positionY }) => ({ id, zoneId, objectId, depth, positionX, positionY }))
  }
  gameStore.connection?.emit('gm:zone_editor:zone:update', data)
  if (zoneEditorStore.isSettingsModalShown) {
    zoneEditorStore.toggleSettingsModal()
  }
}

function clear() {
  tileArray.value.forEach((row, y) => row.forEach((_, x) => placeTile(zoneTilemap.value, tiles.value, x, y, 'blank_tile')))
  tileArray.value = createTileArray()
  zoneEventTiles.value = []
  zoneObjects.value = []
}

function updateZoneObjectDepth(depth: number) {
  zoneObjects.value = zoneObjects.value.map((object) => (object.id === selectedZoneObject.value?.id ? { ...object, depth } : object))
}

function deleteZoneObject(objectId: string) {
  zoneObjects.value = zoneObjects.value.filter((object) => object.id !== objectId)
}

function handleMove() {
  console.log('move btn clicked')
}

onBeforeMount(() => {
  tileArray.value.forEach((row, y) => row.forEach((_, x) => placeTile(zoneTilemap.value, tiles.value, x, y, 'blank_tile')))

  if (zone.value?.tiles) {
    setAllTiles(zoneTilemap.value, tiles.value, zone.value.tiles)
    tileArray.value = zone.value.tiles.map((row) => row.map((tileId) => tileId || 'blank_tile'))
  }

  zoneEventTiles.value = zone.value?.zoneEventTiles ?? []
  zoneObjects.value = zone.value?.zoneObjects ?? []

  // Center camera
  const centerY = (zoneTilemap.value.height * zoneTilemap.value.tileHeight) / 2
  const centerX = (zoneTilemap.value.width * zoneTilemap.value.tileWidth) / 2
  scene.cameras.main.centerOn(centerX, centerY)
})

onBeforeUnmount(() => {
  zoneEventTiles.value = []
  zoneObjects.value = []
  tiles.value.destroy()
  zoneTilemap.value.removeAllLayers()
  zoneTilemap.value.destroy()
  zoneEditorStore.reset()
})
</script>
