using System.Linq;
using Cirno.Scripts.Resources;
using Godot;
using Godot.Collections;
using GTweens.Builders;
using GTweensGodot.Extensions;

namespace Cirno.Scripts.Interactables;

public partial class ItemPickup : Interactable
{
    [Export] public Array<LootItem> LootTable = [];

    private bool _autoPickup = false;

    public bool AutoPickup => _autoPickup;

    public ItemDrop Parent { get; set; } = null;

    public override void _Ready()
    {
        _autoPickup = LootTable.Any(x => x.AutoPickup);
        // if (LootTable.Any(x => x.AutoPickup))
        // {
        //     _autoPickup = true;
        // }

        //this.AreaEntered += _on_area_entered;
    }

    public override bool Activate(ActivationType activationType = ActivationType.Toggle)
    {
        GD.Print("Attempting to Pickup Item");

        if (!MeetsRequirements()) return false;
        Collect();

        return true;
    }

    public void AddItemsToInventory()
    {
        var failedItems = new Array<LootItem>();
        foreach (var item in LootTable)
        {
            if (!InventoryManager.Instance.AddItem(item))
            {
                failedItems.Add(item);
            }
        }

        if (failedItems.Count > 0)
        {
            foreach (var failedItem in failedItems)
            {
                var dup = this.Duplicate() as ItemPickup;
                this.AddSibling(dup);
                dup.LootTable = [failedItem];
            }
        }

        // Delet This

        QueueFree();
    }

    public void Collect()
    {
        AddItemsToInventory();
        // if (Owner is ItemDrop dropWrapper)
        // {
        //     // move the wrapper
        //     var tween = GTweenSequenceBuilder.New()
        //         .Append(dropWrapper.TweenGlobalPosition(GameManager.Instance.PlayerPosition.Value, 0.5f))
        //         .AppendCallback(() =>
        //         {
        //             AddItemsToInventory();
        //             Owner.QueueFree();
        //         })
        //         .Build();
        // }
        // else
        // {
        //     // move this
        //     
        // }
    }

    private void _on_area_entered(Area2D area)
    {
        // if (!_autoPickup) return;
        // if (area is InteractionController interactionController)
        // {
        //     //Check if items are not maxed to avoid a looping autopickup situation
        //     var canAdd = LootTable.Aggregate(false, (current, item) => current || InventoryManager.Instance.CanAddItem(item.ItemKey));
        //
        //     if (canAdd)
        //     {
        //         AddItemsToInventory();
        //     }
        // }
    }

    public void SetSprite(Texture2D sprite)
    {
        var spriteNode = GetNodeOrNull<Sprite2D>("Sprite2D");
        if (spriteNode is null) return;
        spriteNode.Texture = sprite;
    }
}