using Cirno.Scripts.Components.Actors;
using Cirno.Scripts.Interactables;
using Cirno.Scripts.Resources;
using Godot;
using Godot.Collections;

namespace Cirno.Scripts.Components.FSM.Player;

public partial class DeathItemDropper : Node2D
{
    [Export] public PlayerStorageModule Storage { get; private set; }
    [Export] public ActorResourceProvider HealthProvider { get; private set; }

    [Export] public Array<LootItem> ItemsToDrop { get; private set; } = [];

    [Export(PropertyHint.None, "suffix:%")] public float PercentageToDrop { get; private set; } = 50f; 
    
    [Export(PropertyHint.None, "suffix:%")] public float PercentageToDelete { get; private set; } = 50f;
    
    private readonly StringName _dropPhysicsWrapperScene = "uid://d3hds3dbosfcm";
    
    [Export] public float DropRadius { get; private set; } = 8f;
    
    [Export] public float DropSpeed { get; set; } = 40f;

    private PackedScene _loadedDropScene;
    
    public override void _Ready()
    {
        HealthProvider.ResourceDepleted += HealthProviderOnResourceDepleted;
        
        _loadedDropScene = GD.Load<PackedScene>(_dropPhysicsWrapperScene);
    }

    public override void _ExitTree()
    {
        HealthProvider.ResourceDepleted -= HealthProviderOnResourceDepleted;
    }
    
    private void HealthProviderOnResourceDepleted()
    {
        foreach (var item in ItemsToDrop)
        {
            if (InventoryManager.Instance.TryGetItem(item.ItemKey, out var itm))
            {
                var amountToDrop = Mathf.RoundToInt(itm.Count * PercentageToDrop / 100f);

                var removedAmount = InventoryManager.Instance.RemoveItem(item.ItemKey, amountToDrop);
                
                var toDelete = Mathf.RoundToInt(removedAmount * PercentageToDelete / 100f);
                
                DropItem(item, removedAmount - toDelete);
            }
        }
    }
    
    private void DropItem(LootItem item, int amountToDrop)
    {
        if (!string.IsNullOrWhiteSpace(item.DropScenePath))
        {
            for (int i = 0; i < amountToDrop; i++)
            {
                GD.Print($"Dropped item: {item.ItemName}");
                
                var dropInstance = Storage.Root.CreateSibling<ItemDrop>(_loadedDropScene);
                dropInstance.ItemToDrop = item;
                dropInstance.StartingSpeed = DropSpeed;
            }
        }
        else
        {
            GD.Print($"Skipping Item with missing path: {item.ItemName}");
        }
    }
}