using UnityEngine;
using UnityEngine.UIElements;
using VOID.Generic.SaveLoad;

namespace VOID.UserInterface.MainMenu
{
    public class ProfileSelectorUI : MonoBehaviour
    {
        public static ProfileSelectorUI current { get; private set; }
        
        // Visual Elements
        private VisualElement _rootElement;
        private Button _closeButton;
        private VisualElement _profileListElement;
        private TextField _profileAddNameTextField;
        private Button _profileAddButton;
        
        private void Awake()
        {
            current = this;

            var uiDocument = gameObject.GetComponent<UIDocument>();
            var templateElement = uiDocument.rootVisualElement;
            
            // Find all important elements
            _rootElement = templateElement.Q("root-profile-selector"); 
            _closeButton = templateElement.Q<Button>("close");
            _closeButton.clicked += Close;
            _profileListElement = templateElement.Q<VisualElement>("profile-list"); 
            _profileAddNameTextField = templateElement.Q<TextField>("profile-add-name"); 
            _profileAddButton = templateElement.Q<Button>("profile-add");
            _profileAddButton.clicked += AddProfile;
            
            Close();
        }

        public void Open()
        {
            Close();
            
            // Show if hidden
            _rootElement.style.display = DisplayStyle.Flex;

            // Populate UI with existing profiles
            PlayerProfileManager.current.GetProfiles().ForEach(profile =>
                ProfileUI.InitNew(gameObject, _profileListElement, profile, SelectProfile, DeleteProfile));
        }

        public void Close()
        {
            // Close profile selector and clear its content
            _profileListElement.Clear();
            _rootElement.style.display = DisplayStyle.None;
        }

        public void Toggle()
        {
            if (_rootElement.style.display == DisplayStyle.Flex)
                Close();
            else
                Open();
        }

        private void SelectProfile(PlayerProfile profile)
        {
            PlayerProfileManager.current.SelectProfile(profile);
            Close();
        }

        private void DeleteProfile(PlayerProfile profile)
        {
            PlayerProfileManager.current.DeleteProfile(profile);
        }

        private void AddProfile()
        {
            // Init and add new profile to list
            var profile = PlayerProfileManager.current.CreateProfile(_profileAddNameTextField.text);
            ProfileUI.InitNew(gameObject, _profileListElement, profile, SelectProfile, DeleteProfile);
            
            // Clear text field
            _profileAddNameTextField.SetValueWithoutNotify("");
        }
    }
}
