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

  <Container :depth="2">
    <Image
      v-for="object in zoneObjects"
      :depth="object.depth"
      :key="object.object.id"
      :x="tileToWorldX(zoneTilemap, object.position_x, object.position_y)"
      :y="tileToWorldY(zoneTilemap, object.position_x, object.position_y)"
      :texture="object.object.id"
      :originY="Number(object.object.origin_x)"
      :originX="Number(object.object.origin_y)"
    />
  </Container>

  <Container :depth="3">
    <Image v-for="zoneEventTile in zoneEventTiles" :key="zoneEventTile.id" :x="tileToWorldX(zoneTilemap, zoneEventTile.position_x, zoneEventTile.position_y)" :y="tileToWorldY(zoneTilemap, zoneEventTile.position_x, zoneEventTile.position_y)" :texture="zoneEventTile.type" />
  </Container>

  <Toolbar :layer="tiles" @eraser="eraser" @pencil="pencil" @paint="paint" @clear="clear" @save="save" />
  <Tiles v-if="((zoneEditorStore.tool === 'pencil' || zoneEditorStore.tool === 'eraser') && zoneEditorStore.drawMode === 'tile') || zoneEditorStore.tool === 'paint'" />
  <Objects v-if="(zoneEditorStore.tool === 'pencil' || zoneEditorStore.tool === 'eraser') && zoneEditorStore.drawMode === 'object'" />
  <ZoneSettings v-if="zoneEditorStore.isSettingsModalShown" />
  <ZoneList v-if="zoneEditorStore.isZoneListModalShown" />
</template>

<script setup lang="ts">
import config from '@/config'
import { Container, Image, TilemapLayer as TilemapLayerC, useScene } from 'phavuer'
import { onBeforeMount, onBeforeUnmount, ref, toRaw, watch } from 'vue'
import Controls from '@/components/utilities/Controls.vue'
import { useGameStore } from '@/stores/game'
import Toolbar from '@/components/utilities/zoneEditor/Toolbar.vue'
import Tiles from '@/components/utilities/zoneEditor/Tiles.vue'
import { useZoneEditorStore } from '@/stores/zoneEditor'
import ZoneSettings from '@/components/utilities/zoneEditor/ZoneSettings.vue'
import { placeTile, setAllTiles, tileToWorldX, tileToWorldY } from '@/services/zone'
import { useAssetStore } from '@/stores/assets'
import Objects from '@/components/utilities/zoneEditor/Objects.vue'
import type { Zone, ZoneEventTile, ZoneObject } from '@/types'
import { storeToRefs } from 'pinia'
import ZoneList from '@/components/utilities/zoneEditor/ZoneList.vue'
import Tileset = Phaser.Tilemaps.Tileset
import TilemapLayer = Phaser.Tilemaps.TilemapLayer

function uuidv4() {
  return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (+c / 4)))).toString(16))
}

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

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

/**
 * These variables are used to store the tileset images and the tilemap
 * The tilesetImages are used to store the tileset images
 * The zoneTilemap is used to store the tilemap
 * The zoneTiles are used to store the tile data
 * The zoneObjects are used to store the object data
 */
const tilesetImages: Tileset[] = []
const zoneTilemap = new Phaser.Tilemaps.Tilemap(scene, zoneData)
let zoneTiles = [] as string[][]
const zoneObjects = ref<ZoneObject[]>([])
const zoneEventTiles = ref<ZoneEventTile[]>([])

/**
 * Walk through object and add them to the zone as tilesetImages
 */
let tileCount = 1
toRaw(assetStore.assets).forEach((asset) => {
  if (asset.group !== 'tiles') return
  tilesetImages.push(zoneTilemap.addTilesetImage(asset.key, asset.key, config.tile_size.x, config.tile_size.y, 0, 0, tileCount++) as Tileset)
})
tilesetImages.push(zoneTilemap.addTilesetImage('blank_tile', 'blank_tile', config.tile_size.x, config.tile_size.y, 0, 0, 0) as Tileset)

const tiles = zoneTilemap.createBlankLayer('tiles', tilesetImages, 0, config.tile_size.y) as TilemapLayer
const exampleTilesArray = Array.from({ length: zoneEditorStore.zone?.width ?? 0 }, () => Array.from({ length: zoneEditorStore.zone?.height ?? 0 }, () => 'blank_tile'))

const { objectList } = storeToRefs(zoneEditorStore)

/**
 * Watch for object updates and update the zoneObjects
 */
watch(objectList, (newObjects) => {
  zoneObjects.value = zoneObjects.value.map((object) => {
    const newObject = newObjects.find((newObject) => newObject.id === object.object.id)
    if (!newObject) return object
    return { ...object, object: newObject }
  })
})

function eraser(tile: Phaser.Tilemaps.Tile) {
  if (zoneEditorStore.drawMode === 'tile') {
    placeTile(zoneTilemap, tiles, tile.x, tile.y, 'blank_tile')
    zoneTiles[tile.y][tile.x] = 'blank_tile'
  }

  if (zoneEditorStore.drawMode === 'object') {
    /**
     * @TODO : when reloaded in zone editor, these aren't removed
     */
    zoneObjects.value = zoneObjects.value.filter((object) => {
      return object.position_x !== tile.x || object.position_y !== tile.y
    })
  }

  if (zoneEditorStore.drawMode === 'blocking tile') {
    zoneEventTiles.value = zoneEventTiles.value.filter((zoneTileEvent) => {
      return zoneTileEvent.position_x !== tile.x || zoneTileEvent.position_y !== tile.y
    })
  }
}

function pencil(tile: Phaser.Tilemaps.Tile) {
  if (zoneEditorStore.drawMode === 'tile') {
    if (zoneEditorStore.selectedTile === null) return
    placeTile(zoneTilemap, tiles, tile.x, tile.y, zoneEditorStore.selectedTile.id)
    zoneTiles[tile.y][tile.x] = zoneEditorStore.selectedTile.id
  }

  if (zoneEditorStore.drawMode === 'object') {
    if (zoneEditorStore.zone === null) return
    if (zoneEditorStore.selectedObject === null) return

    zoneObjects.value.push({
      id: uuidv4(),
      zoneId: zoneEditorStore.zone.id,
      zone: zoneEditorStore.zone,
      objectId: zoneEditorStore.selectedObject.id,
      object: zoneEditorStore.selectedObject,
      depth: zoneEditorStore.objectDepth,
      position_x: tile.x,
      position_y: tile.y
    })

    // remove duplicates based on object, pos x and y
    zoneObjects.value = zoneObjects.value.filter((object, index, self) => index === self.findIndex((t) => t.objectId === object.objectId && t.position_x === object.position_x && t.position_y === object.position_y))
  }

  if (zoneEditorStore.drawMode === 'blocking tile') {
    if (zoneEditorStore.zone === null) return

    zoneEventTiles.value.push({
      id: uuidv4(),
      zoneId: zoneEditorStore.zone.id,
      zone: zoneEditorStore.zone,
      type: 'BLOCK',
      position_x: tile.x,
      position_y: tile.y
    })

    // remove duplicates based on type, pos x and y
    zoneEventTiles.value = zoneEventTiles.value.filter((zoneTileEvent, index, self) => index === self.findIndex((t) => t.type === zoneTileEvent.type && t.position_x === zoneTileEvent.position_x && t.position_y === zoneTileEvent.position_y))
  }
}

function paint(tile: Phaser.Tilemaps.Tile) {
  if (zoneEditorStore.selectedTile === null) return
  exampleTilesArray.forEach((row, y) => row.forEach((tile, x) => placeTile(zoneTilemap, tiles, x, y, zoneEditorStore.selectedTile.id)))
  zoneTiles.forEach((row, y) => row.forEach((tile, x) => (zoneTiles[y][x] = zoneEditorStore.selectedTile.id)))
}

function save() {
  if (!zoneEditorStore.zone) return

  const data = {
    zoneId: zoneEditorStore.zone.id,
    name: zoneEditorStore.zone.name,
    width: zoneEditorStore.zone.width,
    height: zoneEditorStore.zone.height,
    tiles: zoneTiles,
    zoneEventTiles: toRaw(zoneEventTiles.value).map((tile) => ({
      id: tile.id,
      zoneId: tile.zoneId,
      type: tile.type,
      position_x: tile.position_x,
      position_y: tile.position_y
    })),
    zoneObjects: toRaw(zoneObjects.value).map((obj) => ({
      id: obj.id,
      zoneId: obj.zoneId,
      objectId: obj.objectId,
      depth: obj.depth,
      position_x: obj.position_x,
      position_y: obj.position_y
    }))
  }

  gameStore.connection.emit('gm:zone_editor:zone:update', data)

  gameStore.connection.emit('gm:zone_editor:zone:request', { zoneId: zoneEditorStore.zone.id }, (response: Zone) => {
    zoneEditorStore.setZone(response)
  })

  if (zoneEditorStore.isSettingsModalShown) {
    zoneEditorStore.toggleSettingsModal()
  }
}

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

onBeforeMount(() => {
  exampleTilesArray.forEach((row, y) => row.forEach((tile, x) => placeTile(zoneTilemap, tiles, x, y, 'blank_tile')))
  zoneTiles = exampleTilesArray

  if (zoneEditorStore.zone && zoneEditorStore.zone.tiles) {
    setAllTiles(zoneTilemap, tiles, zoneEditorStore.zone.tiles)
    zoneTiles = zoneEditorStore.zone.tiles

    // Determine the current zone dimensions
    const currentZoneWidth = zoneEditorStore.zone.width ?? 0
    const currentZoneHeight = zoneEditorStore.zone.height ?? 0

    // Ensure zoneTiles matches the current zone dimensions, filling new spaces with 'blank_tile'
    for (let y = 0; y < currentZoneHeight; y++) {
      zoneTiles[y] = zoneTiles[y] || [] // Ensure the row exists
      for (let x = 0; x < currentZoneWidth; x++) {
        zoneTiles[y][x] = zoneTiles[y][x] || 'blank_tile' // Fill missing tiles with 'blank_tile'
      }
    }

    // Update the tilemap with any new 'blank_tile' entries
    zoneTiles.forEach((row, y) => {
      row.forEach((tileId, x) => {
        placeTile(zoneTilemap, tiles, x, y, tileId)
      })
    })
  }

  zoneEventTiles.value = zoneEditorStore.zone?.zoneEventTiles ?? []
  zoneObjects.value = zoneEditorStore.zone?.zoneObjects ?? []
})

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

// center camera
const centerY = (zoneTilemap.height * zoneTilemap.tileHeight) / 2
const centerX = (zoneTilemap.width * zoneTilemap.tileWidth) / 2
scene.cameras.main.centerOn(centerX, centerY)
</script>
