using Cirno.Scripts.Interactables;
using Cirno.Scripts.Resources;
using Godot;

namespace Cirno.Scripts.Components.FSM.Enemy;

public partial class EnemyDropsProvider : Node2D
{
    //private RandomNumberGenerator _rng = new();

    [Export] public float DropRadius { get; private set; } = 8f;
    
    [Export] public float DropSpeed { get; set; } = 40f;
    
    [Export]
    public EnemyStorageModule StorageModule { get; private set; }

    private readonly StringName _dropPhysicsWrapperScene = "uid://d3hds3dbosfcm";
    
    public void DropLoot()
    {
        foreach (var loot in StorageModule.LootDrops)
        {
            if (loot is { Item: not null })
            {
                float roll = (float)GD.RandRange(0d, 100d); // Generate a number between 0 and 100
                if (roll <= loot.Chance) // Compare with drop chance
                {
                    DropItem(loot.Item);
                }
            }
        }
    }
    
    private void DropItem(LootItem item)
    {
        if (!string.IsNullOrWhiteSpace(item.DropScenePath))
        {
            GD.Print($"Dropped item: {item.ItemName}");
            var dropScene = GD.Load<PackedScene>(_dropPhysicsWrapperScene);
            var dropInstance = StorageModule.Root.CreateSibling<ItemDrop>(dropScene);
            dropInstance.ItemToDrop = item;
            dropInstance.StartingSpeed = DropSpeed;
            
            // var scene = GD.Load<PackedScene>(item.DropScenePath);
            // var droppedItem = StorageModule.Root.CreateSibling<Node2D>(scene);
            //
            // // Generate random point within DropRadius
            // float angle = _rng.RandfRange(0, Mathf.Tau); // Random angle (0 to 2π)
            // float radius = _rng.RandfRange(0, DropRadius); // Random radius within range
            //     
            // // Convert polar to cartesian coordinates
            // float xOffset = radius * Mathf.Cos(angle);
            // float yOffset = radius * Mathf.Sin(angle);
            //     
            // Vector2 spawnPosition = StorageModule.Root.GlobalPosition + new Vector2(xOffset, yOffset);
            //
            // droppedItem.GlobalPosition = spawnPosition;
        }
        else
        {
            GD.Print($"Skipping Item with missing path: {item.ItemName}");
        }
    }
}