using Connected.Models.Modal;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;

namespace Connected.Components;
public partial class ReturnModal<ReturnType>
{
	[Parameter]
	public bool Visible { get; set; } = false;

	[Parameter]
	public EventCallback<bool> VisibleChanged { get; set; }

	[Parameter]
	public string Title { get; set; } = string.Empty;

	[Parameter]
	public RenderFragment? ChildContent { get; set; }
	protected bool OverlayClickToClose { get; set; } = true;

	private ReturnType initialValue { get; set; }

	[Parameter]
	public ReturnType Value { get; set; } = default;

	[Parameter]
	public EventCallback<ReturnType> ValueChanged { get; set; }

	protected ModalOptions? ModalOptions { get; set; }

	public async Task CloseModal(bool returnResult = false)
	{
		Visible = false;
		VisibleChanged.InvokeAsync(Visible);
		Title = "";
		ChildContent = null;
		StateHasChanged();
		if (!returnResult)
			await ValueChanged.InvokeAsync(initialValue);
		else
			initialValue = Value;
	}


	public void CheckEscape(KeyboardEventArgs args)
	{
		if (!ModalOptions.DisableEscKey)
		{
			var key = args.Key.ToLower();
			if (key.Equals("escape"))
			{
				CloseModal();
			}
		}
	}

	public void CloseIfEnabled(MouseEventArgs args)
	{
		CloseModal();
	}

	public void PreventClose(MouseEventArgs args)
	{
		OverlayClickToClose = false;
	}

	protected override async Task OnInitializedAsync()
	{
			initialValue = Value;
	}
}