using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using VOID.ScriptableObjects.Player;

namespace VOID.UserInterface.Game.LevelUp
{
    public class LevelUpUI : MonoBehaviour
    {
        public static LevelUpUI current { get; private set; }
        
        // Children - Options
        private List<LevelUpOptionUI> _options = new();

        // Visual Elements
        private VisualElement _rootElement;
        private VisualElement _optionListElement;
        private Button _closeButton;
        
        private void Awake()
        {
            current = this;

            var uiDocument = gameObject.GetComponent<UIDocument>();
            var templateElement = uiDocument.rootVisualElement;

            _rootElement = templateElement.Q("root-level-up");
            _closeButton = _rootElement.Q<Button>("close");
            _optionListElement = _rootElement.Q("options");
            
            _rootElement.dataSource = this;
            _rootElement.pickingMode = PickingMode.Position;

            _closeButton.clicked += Close;
            
            Close();
        }

        public void Open(List<LevelUpOption> options, Action<LevelUpOption> onOptionSelect)
        {
            Close();
            
            _rootElement.style.display = DisplayStyle.Flex;

            foreach (var option in options)
            {
                var optionUI = LevelUpOptionUI.InitNew(gameObject, _optionListElement, option);
                optionUI.OnSelect += Close;
                optionUI.OnSelect += () => onOptionSelect.Invoke(option);
                _options.Add(optionUI);
            }
        }

        public void Close()
        {
            _rootElement.style.display = DisplayStyle.None;
            _optionListElement.Clear();
            _options.ForEach(Destroy);
        }
    }
}
