extends CharacterBody2D


var speed = 100.0

var health: float = 10.0
var hunger: int = 100
var dtps: int = 0 # Damage Taken Per Second

var cooldown_left = 0.0

@onready var tileMap = get_tree().get_first_node_in_group("Ground")
@onready var buildables = get_tree().get_first_node_in_group("Buildables")

@onready var held_item: Node2D = $Held
@onready var held_sprite: Sprite2D = %Held_Sprite
@onready var sprite: AnimatedSprite2D = $Sprite
@onready var item_anim: AnimationPlayer = %Item_Anim
@onready var lbl_coords: Label = %coords

var damage_sprite_time_left: float = 0.0

@onready var food_bar: TextureProgressBar = %food_bar
@onready var health_bar: TextureProgressBar = %health_bar

const FIST = preload("uid://8ngligu3actl")

@export var inventory : Inv

@export var item_anim_playing = false

# Drops and stuff
const DROP = preload("uid://b77km8ca6jhyl")
const STRAWBERRY = preload("uid://b7brn2j4xyq4v")

# Held item stats
var damage: int = 1
var mining_speed: int = 0
var chopping_speed: int = 0
var cooldown: float = 0.75
var food_val: int = 0

func _ready() -> void:
	inventory.update.connect(_update_held_item)
	_update_held_item()

func _physics_process(delta: float) -> void:
	
	_handle_current_tile()
	
	if cooldown_left > 0:
		cooldown_left -= delta
	
	if damage_sprite_time_left > 0:
		damage_sprite_time_left -= delta
	
	# coords neerzetten
	lbl_coords.text = "X: " + str(round(global_position.x / 32)) + "\nY: " + str(round(global_position.y * -1 / 32))

	# Check voor item gebruik
	if Input.is_action_just_pressed("use"):
		_handle_item_usage()
		
	# Beweging
	var direction := Input.get_axis("left", "right")
	var direction_up := Input.get_axis("up", "down")
	if direction or direction_up:
		var total: Vector2 = Vector2(direction, direction_up).normalized()
		velocity.x = total.x * speed
		velocity.y = total.y * speed
		if damage_sprite_time_left <= 0:
			sprite.play("walk")
	else:
		velocity.x = 0
		velocity.y = 0
		if damage_sprite_time_left <= 0:
			sprite.play("default")
	
	if !item_anim_playing:
		held_item.look_at(get_global_mouse_position())
		held_item.rotation_degrees += 45

	move_and_slide()

func collect(item):
	inventory.insert(item)

func _handle_item_usage():
	if !item_anim_playing and cooldown_left <= 0:
		item_anim.play("Use")
		var hand_slot = inventory.slots[18]
		var item = hand_slot.item
		
		if item != null and item.tool_type == "food":
			hand_slot.amount -= 1
			hunger += item.food_val
			food_bar.value = hunger
			if hand_slot.amount <= 0:
				hand_slot.item = null
			%Inventory_UI.update_slots()
			_update_held_item()
		
		cooldown_left += cooldown
	
	var tile_pos_buildables = buildables.local_to_map(get_global_mouse_position())
	var tile_data_buildables = buildables.get_cell_atlas_coords(tile_pos_buildables)
	if tile_data_buildables == Vector2i(0,0):
		buildables.erase_cell(tile_pos_buildables)
		for amount in range(randi_range(1, 5)):
			var drop = DROP.instantiate()
			drop.global_position = get_global_mouse_position()
			drop.global_position += Vector2(randf_range(-8,8), randf_range(-8,8))
			drop.item = STRAWBERRY
			get_tree().current_scene.add_child(drop)
	

func _handle_current_tile():
	var tile_pos = tileMap.local_to_map(global_position)
	var tile_data = tileMap.get_cell_atlas_coords(tile_pos)
	
	match tile_data:
		Vector2i(0,0): # grass
			speed = 100
		Vector2i(1,0): # high grasss
			speed = 80
		Vector2i(2,0): # shallow water
			speed = 80
		Vector2i(3,0): # water
			speed = 40
		Vector2i(4,0): # sand
			speed = 95
		Vector2i(5,0): # mountain
			speed = 0
		Vector2i(6,0): # snow
			speed = 95

func _update_held_item():
	var hand_slot = inventory.slots[18]
	if hand_slot and hand_slot.item:
		held_sprite.texture = hand_slot.item.texture
		cooldown = hand_slot.item.cooldown
		damage = hand_slot.item.damage
		chopping_speed = hand_slot.item.chopping_speed
		mining_speed = hand_slot.item.mining_speed
	else:
		held_sprite.texture = FIST
		cooldown = 0.75
		damage = 1
		chopping_speed = 2
		mining_speed = 1


func _on_hurtbox_area_entered(area: Area2D) -> void:
	if area.is_in_group("Hitbox"):
		var enemy_damage = area.get_parent().damage
		dtps += enemy_damage

func _on_hurtbox_area_exited(area: Area2D) -> void:
	if area.is_in_group("Hitbox"):
		var enemy_damage = area.get_parent().damage
		dtps -= enemy_damage


func _on_stat_update_timeout() -> void:
	if dtps > 0:
		health -= dtps
		damage_sprite_time_left = 0.2
		sprite.play("hurt")

	hunger = clamp(hunger - 1, 0, 100)
	food_bar.value = hunger
	if hunger >= 90:
		health += 0.25
		health = clamp(health, 0, 10)
	elif hunger <= 0:
		health -= 1
	
	if health <= 0:
		_death()
	
	health_bar.value = health

func _death():
	Global.scene_to_load = "res://Scenes/main_menu.tscn"
	get_tree().change_scene_to_file("res://Scenes/loading_screen.tscn")
	
	for items in inventory.slots:
		items.item = null
		items.amount = 0
