using Godot;
using System;
using Cirno.Scripts.Resources;
using Cirno.Scripts.Resources.DebugMenu;
using Godot.Collections;
using DebugMapSelectData = Cirno.Scripts.Resources.DebugMenu.DebugMapSelectData;

public partial class DebugMenu : MenuBase
{
	[Export]
	public Theme ButtonTheme { get; private set; }

	[Export]
	public DebugMapSelectData Levels { get; set; }

	[Export]
	public Container ButtonsContainer { get; private set; }
	
	[Export]
	public Container CheatsContainer { get; private set; }
	
	[Export]
	public Button DefaultSelectedButton { get; private set; }

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		if (GameManager.Instance is not null)
		{
			GameManager.Instance.GameStateChange += OnGameStateChange;
		}
		
		DefaultSelectedButton.GrabFocus();
		
		foreach (var level in Levels.Maps)
		{
			if (!level.Enabled) continue;

			var button = MakeButton(ButtonsContainer, level.DisplayName, level.Icon);
			
			// var button = new Button();
			// //button.Text = level.Split("/")[^1].Split(".")[0];
			// button.Text = level.DisplayName;
			// button.Icon = level.Icon;
			// //button.Text = level;
			// button.Theme = ButtonTheme;
			//
			// ButtonsContainer.CallDeferred("add_child", button);

			button.Pressed += () => ButtonOnPressed(level);
		}

		var refillHealthButton = MakeButton(CheatsContainer, "Health", null);
		refillHealthButton.Pressed += RefillHealthButtonOnPressed;
		
		var refillShieldButton = MakeButton(CheatsContainer, "Shield", null);
		refillShieldButton.Pressed += RefillShieldButtonOnPressed;

	}

	private void OnGameStateChange(GameState state)
	{
		if (state is not GameState.Paused)
		{
			GameManager.Instance.GameStateChange -= OnGameStateChange;
			CloseMenu();
		}
		
	}

	private void RefillHealthButtonOnPressed()
	{
		GameManager.Instance?.Player?.RefillHealth();
	}
	
	private void RefillShieldButtonOnPressed()
	{
		GameManager.Instance?.Player?.RefilleShield();
	}

	private Button MakeButton(Control parent, string text, Texture2D icon)
	{
		var button = new Button();
		button.Text = text;
		button.Icon = icon;
		button.Theme = ButtonTheme;
		parent.CallDeferred("add_child", button);
		return button;
	}

	private void ButtonOnPressed(DebugMapSelectResource scene)
	{
		if (GameManager.Instance is not null)
		{
			GameManager.Instance.Unpause();
		}
		GlobalState.Instance.GoToScene(scene.ScenePath, scene.StartData);
	}

	private void _on_check_box_toggled(bool state)
	{
		GlobalState.Instance.SessionSettings.SkipDialogues = state;
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}
}
