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

namespace VOID.UserInterface.MainMenu
{
    public class MainMenuUI : MonoBehaviour
    {
        public static MainMenuUI current { get; private set; }
        
        // Visual Elements
        private VisualElement _rootElement;
        private Button _newGameButton;
        private Button _profileButton;
        private Label _currentProfileLabel;
        private Button _settingsButton;
        private Button _exitButton;
        
        private void Awake()
        {
            current = this;

            var uiDocument = gameObject.GetComponent<UIDocument>();
            var templateElement = uiDocument.rootVisualElement;
            
            // Find all important elements
            _rootElement = templateElement.Q("root-main-menu"); 
            _newGameButton = templateElement.Q<Button>("new-game");
            _newGameButton.clicked += NewGameButton;
            _profileButton = templateElement.Q<Button>("profile");
            _profileButton.clicked += ProfileButton;
            _currentProfileLabel = templateElement.Q<Label>("current-profile-name"); 
            _settingsButton = templateElement.Q<Button>("settings");
            _settingsButton.clicked += SettingsButton;
            _exitButton = templateElement.Q<Button>("exit");
            _exitButton.clicked += ExitButton;
        }

        private void Start()
        {
            // Force update active profile name on game start
            OnProfileChange(PlayerProfileManager.current.activeProfile);
            
            // Update selected profile when we change it
            PlayerProfileManager.current.OnProfileChange += OnProfileChange;
        }

        private void OnProfileChange(PlayerProfile profile)
        {
            _newGameButton.style.opacity = profile != null ? 1f : 0.2f;
            _currentProfileLabel.text = profile != null ? profile.name : "--- BRAK ---";
        }

        private void NewGameButton()
        {
            if (PlayerProfileManager.current.activeProfile == null)
            {
                Debug.LogWarning("Profile not selected!");
                return;
            }
            
            GameLoopManager.current.LoadLobby();
        }

        private void ProfileButton()
        {
            ProfileSelectorUI.current.Toggle();
        }

        private void SettingsButton()
        {
            Debug.Log("TODO: nie ma ustawień :c");
        }

        private void ExitButton()
        {
            Application.Quit();
        }
    }
}
