using Connected.Models.Modal;
using Microsoft.AspNetCore.Components;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;

namespace Connected.Services;
public class ModalDialogService
{
	public event Action<string, RenderFragment, List<ModalButton>, ModalOptions> OnShow;
	public event Action OnClose;

	public void ShowDialog(string title, RenderFragment Content, List<ModalButton> buttons, ModalOptions options)
	{
		var body = Content;
		OnShow?.Invoke(title, body, buttons, options);
	}

	public void ShowDialog<T>(string title, RenderFragment<T> content, T model, List<ModalButton>? buttons = null, ModalOptions? options = null)
	{
		var body = content(model);

		OnShow?.Invoke(title, body, buttons ?? new(), options ?? new());
	}

	public void ShowDialog<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TComponent, TModel>(string title, TModel model, List<ModalButton>? buttons = null, ModalOptions? options = null) where TComponent : Microsoft.AspNetCore.Components.IComponent where TModel : class
	{
		RenderFragment<TModel> fragment = (model) => __builder =>
		{
			__builder.OpenComponent<TComponent>(0);
			__builder.AddAttribute(1, "Model", model);
			__builder.CloseComponent();			
		};

		OnShow?.Invoke(title, fragment(model), buttons ?? new(), options ?? new());
	}

	public void ShowDialog(string title, MarkupString content, List<ModalButton> buttons, ModalOptions options)
	{
		var body = new RenderFragment(x => x.AddContent(1, content));
		OnShow?.Invoke(title, body, buttons, options);
	}

	public void ShowDialog(string title, MarkupString content, List<ModalButton> buttons)
	{
		var body = new RenderFragment(x => x.AddContent(1, content));
		OnShow?.Invoke(title, body, buttons, new ModalOptions());
	}

	public void Close()
	{
		OnClose?.Invoke();
	}
}
