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

<script lang="ts" setup>
import config from '@/application/config'
import { type MapCharacter, type Sprite as SpriteT } 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 { useGameStore } from '@/stores/gameStore'
import { useMapStore } from '@/stores/mapStore'
import { Container, refObj, Sprite, useScene } from 'phavuer'
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'

// import CharacterChest from '@/components/game/character/partials/CharacterChest.vue'

enum Direction {
  POSITIVE,
  NEGATIVE,
  UNCHANGED
}

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

const charContainer = refObj<Phaser.GameObjects.Container>()
const charSprite = refObj<Phaser.GameObjects.Sprite>()

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

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

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

const updatePosition = (x: number, y: number, direction: Direction) => {
  const targetX = tileToWorldX(props.tilemap, x, y)
  const targetY = tileToWorldY(props.tilemap, x, y)

  if (isInitialPosition.value) {
    currentX.value = targetX
    currentY.value = targetY
    isInitialPosition.value = false
    return
  }

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

  const distance = Math.sqrt(Math.pow(targetX - currentX.value, 2) + Math.pow(targetY - currentY.value, 2))

  if (distance >= config.tile_size.x / 1.1) {
    currentX.value = targetX
    currentY.value = targetY
    return
  }

  const duration = distance * 5.7

  tween.value = props.tilemap.scene.tweens.add({
    targets: { x: currentX.value, y: currentY.value },
    x: targetX,
    y: targetY,
    duration,
    ease: 'Linear',
    onStart: () => {
      if (direction === Direction.POSITIVE) {
        updateIsometricDepth(x, y)
      }
    },
    onUpdate: (tween) => {
      currentX.value = tween.targets[0].x
      currentY.value = tween.targets[0].y
    },
    onComplete: () => {
      if (direction === Direction.NEGATIVE) {
        updateIsometricDepth(x, y)
      }
    }
  })
}

const calcDirection = (oldX: number, oldY: number, newX: number, newY: number): Direction => {
  if (newY < oldY || newX < oldX) return Direction.NEGATIVE
  if (newX > oldX || newY > oldY) return Direction.POSITIVE
  return Direction.UNCHANGED
}

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

const charTexture = computed(() => {
  const { rotation, characterType } = props.mapCharacter.character
  const spriteId = characterType?.sprite ?? 'idle_right_down'
  const action = props.mapCharacter.isMoving ? 'walk' : 'idle'
  const direction = [0, 6].includes(rotation) ? 'left_up' : 'right_down'

  return `${spriteId}-${action}_${direction}`
})

const updateSprite = () => {
  if (props.mapCharacter.isMoving) {
    charSprite.value!.anims.play(charTexture.value, true)
    return
  }

  charSprite.value!.anims.stop()
  charSprite.value!.setFrame(0)
  charSprite.value!.setTexture(charTexture.value)
}

watch(
  () => ({
    x: props.mapCharacter.character.positionX,
    y: props.mapCharacter.character.positionY,
    isMoving: props.mapCharacter.isMoving,
    rotation: props.mapCharacter.character.rotation
  }),
  (newValues, oldValues) => {
    if (!newValues) return

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

    // Handle animation updates
    if (newValues.isMoving !== oldValues?.isMoving || newValues.rotation !== oldValues?.rotation) {
      updateSprite()
    }
  },
  { deep: true }
)

watch(() => props.mapCharacter, updateSprite)

loadSpriteTextures(scene, props.mapCharacter.character.characterType?.sprite as string)
  .then(() => {
    charSprite.value!.setTexture(charTexture.value)
    charSprite.value!.setFlipX(isFlippedX.value)
  })
  .catch((error) => {
    console.error('Error loading texture:', error)
  })

onMounted(() => {
  charContainer.value!.setName(props.mapCharacter.character!.name)

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

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

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

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