using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;

namespace Connected.Components;
public partial class TabPanel : UIComponent
{
	#region Event callbacks

	/// <summary>
	/// Raised when tab is clicked
	/// </summary>
	[Parameter] public EventCallback<MouseEventArgs> OnClick { get; set; }

	#endregion

	#region Content placeholders

	/// <summary>
	/// Child content of component.
	/// </summary>
	[Parameter]
	public RenderFragment ChildContent { get; set; }

	/// <summary>
	/// Tab content of component.
	/// </summary>
	[Parameter]
	public RenderFragment TabContent { get; set; }

	/// <summary>
	/// Tab content wrapper of component. It is used to wrap the content of a tab heading in a user supplied div or component. 
	/// Use @context in the TabWrapperContent to render the tab header within your custom wrapper. 
	/// This is most useful with tooltips, which must wrap the entire content they refer to.
	/// </summary>
	[Parameter]
	public RenderFragment<RenderFragment> TabWrapperContent { get; set; }

	/// <summary>
	/// TabPanel Tooltip. It will be ignored if TabContent is provided.
	/// </summary>
	[Parameter]
	public string ToolTip { get; set; }

	private bool _disposed;

	[CascadingParameter] private Tabs Parent { get; set; }

	public ElementReference PanelRef;

	#endregion

	#region Styling properties

	/// <summary>
	/// Text will be displayed in the TabPanel as TabTitle.
	/// </summary>
	[Parameter]
	public string Text { get; set; }

	/// <summary>
	/// Glyph placed before the text if set.
	/// </summary>
	[Parameter]
	public string Icon { get; set; }

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

	/// <summary>
	/// Unique TabPanel ID. Useful for activation when Panels are dynamically generated.
	/// </summary>
	[Parameter]
	public object ID { get; set; }
	#endregion

	#region Lifecycle

	protected override async Task OnAfterRenderAsync(bool firstRender)
	{
		await base.OnAfterRenderAsync(firstRender);
		if (firstRender == true && Parent != null)
		{
			await Parent.SetPanelRef(PanelRef);
		}
	}

	protected override void OnInitialized()
	{
		// NOTE: we must not throw here because we need the component to be able to live for the API docs to be able to infer default values
		//if (Parent == null)
		//    throw new ArgumentNullException(nameof(Parent), "TabPanel must exist within a Tabs component");
		base.OnInitialized();

		Parent?.AddPanel(this);
	}

	public async ValueTask DisposeAsync()
	{
		if (_disposed == true) { return; }

		_disposed = true;
		await Parent?.RemovePanel(this);


	#endregion
	
	}
}
