using Godot;
using System.Collections.Generic;

namespace AceFieldNewHorizon.Scripts.System;

public partial class Hud : CanvasLayer
{
	private ResourceManager _resourceManager;
	private VBoxContainer _resourceDisplay;
	private readonly Dictionary<string, Label> _resourceLabels = new();
	private VBoxContainer _pickupLogContainer;

	public override void _Ready()
	{
		_resourceDisplay = GetNode<VBoxContainer>("ResourceDisplay");
		
		_pickupLogContainer = new VBoxContainer();
		_pickupLogContainer.Name = "PickupLogContainer";
		_pickupLogContainer.SetAnchorsPreset(Control.LayoutPreset.BottomLeft);
		_pickupLogContainer.OffsetLeft = 10;
		_pickupLogContainer.OffsetBottom = -10; // Negative offset from bottom anchor
		_pickupLogContainer.GrowVertical = Control.GrowDirection.Begin; // Make it grow upwards
		AddChild(_pickupLogContainer);
		
		_resourceManager = DependencyInjection.Container.GetInstance<ResourceManager>(); 
		if (_resourceManager == null)
		{
			GD.PushError("ResourceSystem not found in the scene tree!");
			return;
		}

		_resourceManager.OnResourceChanged += UpdateResourceDisplay;
		_resourceManager.OnResourcePickedUp += OnResourcePickedUp;
		
		// Initialize display with current resources
		foreach (var entry in _resourceManager.GetAllResources())
		{
			UpdateResourceDisplay(entry.Key, entry.Value);
		}
	}

	private void UpdateResourceDisplay(string resourceId, int newAmount)
	{
		if (!_resourceLabels.TryGetValue(resourceId, out Label label))
		{
			label = new Label();
			_resourceDisplay.AddChild(label);
			_resourceLabels.Add(resourceId, label);
		}

		if (newAmount <= 0)
		{
			// Remove label if resource amount is zero or less
			if (label.GetParent() != null)
			{
				_resourceDisplay.RemoveChild(label);
			}
			_resourceLabels.Remove(resourceId);
			label.QueueFree(); // Free the label from memory
		}
		else
		{
			label.Text = $"{resourceId}: {newAmount}";
		}
	}

	private void OnResourcePickedUp(string resourceId, int amount)
	{
		AddPickupLogEntry($"Picked up {amount} {resourceId}!");
	}

	private void AddPickupLogEntry(string message)
	{
		var logLabel = new Label();
		logLabel.Text = message;
		_pickupLogContainer.AddChild(logLabel);

		var timer = new Timer();
		timer.WaitTime = 3.0f;
		timer.OneShot = true;
		timer.Autostart = true;
		logLabel.AddChild(timer); // Add timer as child of the label
		timer.Timeout += () => OnLogEntryTimeout(logLabel);
	}

	private void OnLogEntryTimeout(Label logLabel)
	{
		// Start fading out the label
		var tween = logLabel.CreateTween();
		tween.TweenProperty(logLabel, "modulate", new Color(1, 1, 1, 0), 0.5f); // Fade out over 0.5 seconds
		tween.TweenCallback(Callable.From(() => logLabel.QueueFree())); // Free after fading
	}

	public override void _ExitTree()
	{
		if (_resourceManager != null)
		{
			_resourceManager.OnResourceChanged -= UpdateResourceDisplay;
			_resourceManager.OnResourcePickedUp -= OnResourcePickedUp;
		}
	}
}
