using Connected.Enums;
using Connected.Models.Modal;
using Connected.Services;
using Connected.Utilities;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using System.Reflection;

namespace Connected.Components;
public partial class ModalDialog : IDisposable
{
	[Inject] ModalDialogService? ModalService { get; set; }

	protected ElementReference root;
	protected bool IsVisible { get; set; }
	protected string? Title { get; set; }
	protected RenderFragment? Content { get; set; }
	protected bool OverlayClickToClose { get; set; } = true;

	protected List<ModalButton> buttons { get; set; } = new();

	protected ModalOptions? ModalOptions { get; set; }

	[Parameter]
	public string? Class { get; set; }

	private CssBuilder ClassList
	{
		get
		{
			return new CssBuilder()
				.AddClass(Type)
				.AddClass("fade")
				.AddClass("show")				
				.AddClass(Class);
		}
	}

	private string Type
	{
		get
		{
			var type = Helper.GetEnumDescription(ModalOptions?.Type ?? ModalType.Default);

			if (!string.IsNullOrWhiteSpace(type))
				type = $"-{type}";

			return $"modal{type}";
		}
	}

	protected override void OnInitialized()
	{
		ModalService.OnShow += ShowModal;
		ModalService.OnClose += CloseModal;
	}

	protected override async Task OnAfterRenderAsync(bool firstRender)
	{
		if (IsVisible)
			await root.FocusAsync();
	}


	public void ShowModal(string title, RenderFragment content, List<ModalButton> buttons, ModalOptions options)
	{
		Title = title;
		Content = content;
		IsVisible = true;

		ModalOptions = options;
		this.buttons = buttons;

		StateHasChanged();
	}


	public void CloseModal(ModalButton? button)
	{
		if (button is not null)
		{
			if (button.CloseDialogOnClick)
			{
				CloseModal();
			}
			button.OnClickEvent.Delegate.DynamicInvoke(button.OnClickEvent.args);
		}
		StateHasChanged();
	}

	public void CloseModal()
	{
		IsVisible = false;
		Title = "";
		Content = null;
		StateHasChanged();
	}



	public void Dispose()
	{
		if (ModalService is not null)
		{
			ModalService.OnShow -= ShowModal;
			ModalService.OnClose -= CloseModal;
		}
	}

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

	public void CloseIfEnabled(MouseEventArgs args)
	{
		if (!ModalOptions.DisableBackdropClick)
		{
			if (OverlayClickToClose)
			{
				CloseModal();
			}
		}
		OverlayClickToClose = true;
	}

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

}