using Godot;
using Mr.BrickAdventures.Autoloads;

namespace Mr.BrickAdventures.scripts.UI;

public partial class SettingsMenu : Control
{
    [Export] public Control InputSettingsControl { get; set; }
    [Export] public Control AudioSettingsControl { get; set; }
    [Export] public Control DisplaySettingsControl { get; set; }
    [Export] public Control GameplaySettingsControl { get; set; }
    [Export] public Control SettingsMenuControl { get; set; }
    [Export] public Button InputSettingsButton { get; set; }
    [Export] public Button AudioSettingsButton { get; set; }
    [Export] public Button DisplaySettingsButton { get; set; }
    [Export] public Button GameplaySettingsButton { get; set; }

    private UIManager UIManager => UIManager.Instance;

    public override void _Ready()
    {
        InputSettingsButton.FocusMode = FocusModeEnum.All;
        AudioSettingsButton.FocusMode = FocusModeEnum.All;
        DisplaySettingsButton.FocusMode = FocusModeEnum.All;
        GameplaySettingsButton.FocusMode = FocusModeEnum.All;

        InputSettingsButton.Pressed += OnInputSettingsPressed;
        AudioSettingsButton.Pressed += OnAudioSettingsPressed;
        DisplaySettingsButton.Pressed += OnDisplaySettingsPressed;
        GameplaySettingsButton.Pressed += OnGameplaySettingsPressed;

        InputSettingsControl?.Hide();
        AudioSettingsControl?.Hide();
        DisplaySettingsControl?.Hide();
        GameplaySettingsControl?.Hide();

        if (InputDeviceManager.Instance != null)
            InputDeviceManager.Instance.DeviceChanged += OnDeviceChanged;
        VisibilityChanged += OnVisibilityChanged;
    }

    public override void _ExitTree()
    {
        if (InputDeviceManager.Instance != null)
            InputDeviceManager.Instance.DeviceChanged -= OnDeviceChanged;
        VisibilityChanged -= OnVisibilityChanged;
    }

    private void OnVisibilityChanged()
    {
        if (IsVisibleInTree() && InputDeviceManager.Instance?.IsPointerless == true)
            GrabFirstFocus();
    }

    private void OnDeviceChanged(int device)
    {
        var d = (InputDeviceManager.InputDevice)device;
        if (d != InputDeviceManager.InputDevice.Mouse && IsVisibleInTree())
            GrabFirstFocus();
    }

    private void GrabFirstFocus() => InputSettingsButton.GrabFocus();

    public override void _UnhandledInput(InputEvent @event)
    {
        if (!@event.IsActionReleased("ui_cancel")) return;
        if (UIManager.IsScreenOnTop(SettingsMenuControl)) UIManager.PopScreen();
    }

    private void OnInputSettingsPressed()
    {
        UIManager.PushScreen(InputSettingsControl);
    }

    private void OnAudioSettingsPressed()
    {
        UIManager.PushScreen(AudioSettingsControl);
    }

    private void OnDisplaySettingsPressed()
    {
        UIManager.PushScreen(DisplaySettingsControl);
    }

    private void OnGameplaySettingsPressed()
    {
        UIManager.PushScreen(GameplaySettingsControl);
    }
}