using System.Collections.Generic;
using System.Linq;
using Godot;

namespace Cirno.Scripts.UI;

public partial class InventoryMenu : TabContainer
{
    private List<ItemsMenu> _itemMenus = [];
    
    [Export]
    public StringName InventoryActionName { get; private set; } = "inventory";
    
    [Export]
    public StringName PauseActionName { get; private set; } = "pause";
    
    [Export]
    public StringName CancelActionName { get; private set; } = "ui_cancel";
    
    public override void _Ready()
    {
        CallDeferred(MethodName.DeferredInitialize);
        this.Hide();
    }
    
    public override void _Process(double delta)
    {
        if (Input.IsActionJustPressed(InventoryActionName) || Input.IsActionJustPressed(PauseActionName) || Input.IsActionJustPressed(CancelActionName))
        {
            if (Visible)
            {
                GameManager.Instance.ChangeState(GameState.Playing);
                //CallDeferred(MethodName.HideInventory);
            }
            // else
            // {
            //     ShowInventory();
            // }
        }
    }
    
    private void DeferredInitialize()
    {
        var children = this.GetChildren();
        foreach (var child in children)
        {
            if (child is ItemsMenu menu)
            {
                _itemMenus.Add(menu);
                menu.Init(this);
            }
        }
        //Clear();
        
        //ItemActivated += OnItemSelected;

        GameManager.Instance.GameStateChange += state =>
        {
            switch (state)
            {
                case GameState.Inventory:
                    CallDeferred(MethodName.ShowInventory);
                    break;
                default:
                    CallDeferred(MethodName.HideInventory);
                    //HideInventory();
                    break;
            }
        };
    }
    
    private void HideInventory()
    {
        if (!Visible) return;
        GD.Print("Hiding inventory");
        this.Hide();
        foreach (var menu in _itemMenus)
        {
            menu.Empty();
        }
        
        //_itemsDic.Clear();
        
        //GameManager.Instance.ChangeState(GameState.Playing);
    }

    private void ShowInventory()
    {
        if (Visible) return;
        this.Show();
        
        foreach (var menu in _itemMenus)
        {
            menu.Fill();
        }
        
        _itemMenus.FirstOrDefault()?.GrabFocus();
    }
}