using Godot;
using System;
using System.Linq;
using Cirno.Scripts;
using Cirno.Scripts.UI;
using Godot.Collections;

public partial class ItemsMenu : ItemList
{
    private Dictionary<long, string> _itemsDic = new();
    
    [Export] public Array<ItemTypes> ItemsFilter { get; private set; } = [];

    private InventoryMenu _parent;

    
    public void Init(InventoryMenu parent)
    {
        _parent = parent;
        Empty();
        ItemActivated += OnItemSelected;
    }

    public void Fill()
    {
        var sortedItems = InventoryManager.Instance.Items.OrderBy(x => x.Item.ItemKey.ToString()).ToList();
        // If it crashes here I might have forgot to add new items to the itemsdatabase
        foreach (var item in sortedItems)
        {
            if (item.Count <= 0) continue;
            if (!ItemsFilter.Contains(item.Item.Item)) continue;
            
            var index = this.AddItem($"{item.Item.ItemName} x{item.Count}", item.Item.InventorySprite,
                true);
            
            //this.SetItemTooltip(index, item.Item.ItemDescription);
            
            _itemsDic.Add(index, item.Item.ItemKey);
            
        }
    }

    public void Empty()
    {
        Clear();
        _itemsDic.Clear();
    }

    private void OnItemSelected(long index)
    {
        var item = _itemsDic[index];
        GD.Print("Item: " + item);
        InventoryManager.Instance.TryGetItem(item, out var lootItem);
        if (!lootItem.Item.Selectable) return;

        GameManager.Instance.ChangeState(GameState.Playing);
        
        InventoryManager.Instance.UseItem(item);
    }

    // private void HideInventory()
    // {
    //     if (!Visible) return;
    //     GD.Print("Hiding inventory");
    //     this.Hide();
    //     Clear();
    //     _itemsDic.Clear();
    //     
    //     GameManager.Instance.ChangeState(GameState.Playing);
    // }

    // private void ShowInventory()
    // {
    //     if (Visible) return;
    //     this.Show();
    //     GrabFocus();
    //     foreach (var item in _inventoryManager.Items)
    //     {
    //         if (item.Count <= 0) continue;
    //         if (!ItemsFilter.Contains(item.Item.Item)) continue;
    //         
    //         var index = this.AddItem($"{item.Item.ItemName} x{item.Count}", item.Item.InventorySprite,
    //             true);
    //         
    //         this.SetItemTooltip(index, item.Item.ItemDescription);
    //         
    //         _itemsDic.Add(index, item.Item.ItemKey);
    //         
    //     }
    // }
}
