using System.Windows.Input;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;

namespace Connected.Components;

public abstract class ButtonBase : UIComponent
{
	#region EventCallbacks
	/// <summary>
	/// Button click event.
	/// </summary>
	[Parameter]
	public EventCallback<MouseEventArgs> Clicked { get; set; }
	#endregion

	#region Content placeholders
	/// <summary>
	/// Potential activation target for this button. This enables RenderFragments with user-defined
	/// buttons which will automatically activate the intended functionality. 
	/// </summary>
	[CascadingParameter]
	protected IActivatable? Activateable { get; set; }
	#endregion

	#region Styling properties
	#endregion

	#region Behavior properties
	/// <summary>
	/// The button Type (Button, Submit, Refresh)
	/// </summary>
	[Parameter]
	public ButtonType ButtonType { get; set; }

	/// <summary>
	/// Command executed when the user clicks on an element.
	/// </summary>
	[Parameter]
	public ICommand? Command { get; set; }

	/// <summary>
	/// Command parameter.
	/// </summary>
	[Parameter]
	public object? CommandParameters { get; set; }

	/// <summary>
	/// If true, the button will be disabled.
	/// </summary>
	[Parameter]
	public bool Disabled { get; set; }
	#endregion

	/// <summary>
	/// The HTML element that will be rendered in the root by the component
	/// By default, is a button.
	/// </summary>
	protected string HtmlTag => ButtonType.ToString().ToLower();

	/// <summary>
	/// Indicates whether the internal click propagation should be disabled,
	/// as it is handled in the component itself.
	/// </summary>
	protected bool PreventOnClickPropagation => string.Compare(HtmlTag, "button", true) == 0;

	protected async Task OnClick(MouseEventArgs e)
	{
		if (Disabled)
			return;

		if (Clicked.HasDelegate)
			await Clicked.InvokeAsync(e);

		if (Command?.CanExecute(CommandParameters) ?? false)
			Command.Execute(CommandParameters);

		Activateable?.Activate(this, e);
	}
}
