<template>
  <ChatBubble :mapCharacter="props.mapCharacter" :currentX="currentPositionX" :currentY="currentPositionY" />
  <Healthbar :mapCharacter="props.mapCharacter" :currentX="currentPositionX" :currentY="currentPositionY" />
  <CharacterHair :mapCharacter="props.mapCharacter" :currentX="currentPositionX" :currentY="currentPositionY" />
  <Sprite ref="charSprite" :depth="isometricDepth" :x="currentPositionX" :y="currentPositionY" :origin-y="1" :flipX="isFlippedX" />
</template>

<script lang="ts" setup>
import config from '@/application/config'
import { type MapCharacter } from '@/application/types'
import CharacterHair from '@/components/game/character/partials/CharacterHair.vue'
import ChatBubble from '@/components/game/character/partials/ChatBubble.vue'
import Healthbar from '@/components/game/character/partials/Healthbar.vue'
import { loadSpriteTextures } from '@/composables/gameComposable'
import { calculateIsometricDepth, tileToWorldX, tileToWorldY } from '@/composables/mapComposable'
import { CharacterTypeStorage } from '@/storage/storages'
import { useGameStore } from '@/stores/gameStore'
import { useMapStore } from '@/stores/mapStore'
import { refObj, Sprite, useScene } from 'phavuer'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'

enum Direction {
  POSITIVE,
  NEGATIVE,
  UNCHANGED
}

const props = defineProps<{
  tilemap: Phaser.Tilemaps.Tilemap
  mapCharacter: MapCharacter
}>()

const charSprite = refObj<Phaser.GameObjects.Sprite>()
const charSpriteId = ref('')

const gameStore = useGameStore()
const mapStore = useMapStore()
const scene = useScene()

const currentPositionX = ref(0)
const currentPositionY = ref(0)
const isometricDepth = ref(1)
const isInitialPosition = ref(true)
const tween = ref<Phaser.Tweens.Tween | null>(null)

const updateIsometricDepth = (positionX: number, positionY: number) => {
  isometricDepth.value = calculateIsometricDepth(positionX, positionY, 28, 94, true)
}

const updatePosition = (positionX: number, positionY: number, direction: Direction) => {
  const newPositionX = tileToWorldX(props.tilemap, positionX, positionY)
  const newPositionY = tileToWorldY(props.tilemap, positionX, positionY)

  if (isInitialPosition.value) {
    currentPositionX.value = newPositionX
    currentPositionY.value = newPositionY
    isInitialPosition.value = false
    return
  }

  if (tween.value?.isPlaying()) {
    tween.value.stop()
  }

  const distance = Math.sqrt(Math.pow(newPositionX - currentPositionX.value, 2) + Math.pow(newPositionY - currentPositionY.value, 2))

  if (distance >= config.tile_size.width / 1.1) {
    currentPositionX.value = newPositionX
    currentPositionY.value = newPositionY
    return
  }

  const duration = distance * 5.7

  tween.value = props.tilemap.scene.tweens.add({
    targets: { x: currentPositionX.value, y: currentPositionY.value },
    x: newPositionX,
    y: newPositionY,
    duration,
    ease: 'Linear',
    onStart: () => {
      if (direction === Direction.POSITIVE) {
        updateIsometricDepth(positionX, positionY)
      }
    },
    onUpdate: (tween) => {
      // @ts-ignore
      currentPositionX.value = tween.targets[0].x
      // @ts-ignore
      currentPositionY.value = tween.targets[0].y
    },
    onComplete: () => {
      if (direction === Direction.NEGATIVE) {
        updateIsometricDepth(positionX, positionY)
      }
    }
  })
}

const calcDirection = (oldPositionX: number, oldPositionY: number, newPositionX: number, newPositionY: number): Direction => {
  if (newPositionY < oldPositionY || newPositionX < oldPositionX) return Direction.NEGATIVE
  if (newPositionX > oldPositionX || newPositionY > oldPositionY) return Direction.POSITIVE
  return Direction.UNCHANGED
}

const isFlippedX = computed(() => [6, 4].includes(props.mapCharacter.character.rotation ?? 0))

const currentDirection = computed(() => {
  return [0, 6].includes(props.mapCharacter.character.rotation ?? 0) ? 'left_up' : 'right_down'
})

const currentAction = computed(() => {
  return props.mapCharacter.isMoving ? 'walk' : 'idle'
})

const charTexture = computed(() => {
  const spriteId = charSpriteId.value ?? 'idle_right_down'
  return `${spriteId}-${currentAction.value}_${currentDirection.value}`
})

const updateSprite = () => {
  if (!charSprite.value) return

  if (props.mapCharacter.isMoving) {
    charSprite.value.anims.play(charTexture.value, true)
  } else {
    charSprite.value.anims.stop()
    charSprite.value.setFrame(0)
    charSprite.value.setTexture(charTexture.value)
  }
}

const handlePositionUpdate = (newValues: any, oldValues: any) => {
  if (!newValues) return

  if (!oldValues || newValues.positionX !== oldValues.positionX || newValues.positionY !== oldValues.positionY) {
    const direction = !oldValues ? Direction.POSITIVE : calcDirection(oldValues.positionX, oldValues.positionY, newValues.positionX, newValues.positionY)
    updatePosition(newValues.positionX, newValues.positionY, direction)
  }

  if (newValues.isMoving !== oldValues?.isMoving || newValues.rotation !== oldValues?.rotation) {
    updateSprite()
  }
}

watch(
  () => ({
    positionX: props.mapCharacter.character.positionX,
    positionY: props.mapCharacter.character.positionY,
    isMoving: props.mapCharacter.isMoving,
    rotation: props.mapCharacter.character.rotation
  }),
  handlePositionUpdate
)

onMounted(async () => {
  let character = props.mapCharacter.character

  const characterTypeStorage = new CharacterTypeStorage()

  const spriteId = await characterTypeStorage.getSpriteId(character.characterType!)
  if (!spriteId) return

  charSpriteId.value = spriteId

  await loadSpriteTextures(scene, spriteId)

  if (charSprite.value) {
    charSprite.value.setTexture(charTexture.value)
    charSprite.value.setFlipX(isFlippedX.value)
    charSprite.value.setName(props.mapCharacter.character.name)
  }

  if (character.id === gameStore.character!.id) {
    mapStore.setCharacterLoaded(true)

    // #146 : Set camera position to character, need to be improved still
    scene.cameras.main.startFollow(charSprite.value as Phaser.GameObjects.Sprite)
  }

  updatePosition(character.positionX, character.positionY, character.rotation)
})

onUnmounted(() => {
  tween.value?.stop()
})
</script>
