using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using Vaitr.MemoryBus;

namespace Insight.Web.Components.Navbars;

public partial class NavSwitch : IDisposable
{
    [CascadingParameter] public IReadOnlyDictionary<string, object>? RouteValues { get; set; }

    [Inject] private NavigationManager NavigationManager { get; init; } = default!;
    [Inject] private IMemoryBus Bus { get; init; } = default!;

    public string Url { get; set; } = string.Empty;
    private IDisposable? Token { get; set; }
    public bool Disposed { get; set; } = false;

    private enum Content { Main, Account, Customer, Host }
    private Content _content = Content.Main;

    protected override void OnInitialized()
    {
        Token = Bus?.SubscribeAsync<string>(OnRefreshAsync, p => p == Events.Layout.Rendered);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await OnRefreshAsync().ConfigureAwait(false);
        }
    }

    public async ValueTask OnRefreshAsync(string? message = null, CancellationToken cancellationToken = default)
    {
        Url = NavigationManager.ToBaseRelativePath(NavigationManager.Uri);

        if (Url is null) return;

        if (Url.StartsWith($"{Navigation.Account.Index}/")) _content = Content.Account;
        else if (Url.StartsWith($"{Navigation.Management.Customers.Index}/")) _content = Content.Customer;
        else if (Url.StartsWith($"{Navigation.Management.Hosts.Index}/")) _content = Content.Host;
        else _content = Content.Main;

        await InvokeAsync(StateHasChanged).ConfigureAwait(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (Disposed) return;
        Token?.Dispose();
    }
}