@using CommunityToolkit.Mvvm.Messaging
@using SteUp.Shared.Components.SingleElements.MessageBox
@using SteUp.Shared.Core.Enum
@using SteUp.Shared.Core.Interface.LocalDb
@using SteUp.Shared.Core.Messages.Ispezione
@using SteUp.Shared.Core.Messages.Scheda
@inject INetworkService NetworkService
@inject IDialogService Dialog
@inject IMessenger Messenger
@inject IIspezioniService IspezioniService
@inject IJSRuntime Js

<div
    class="container animated-navbar @(IsVisible ? "show-nav" : "hide-nav") @(IsVisible ? PlusVisible ? "with-plus" : "without-plus" : "with-plus")">
    <nav class="navbar @(IsVisible ? PlusVisible ? "with-plus" : "without-plus" : "with-plus")">
        <div class="container-navbar">
            <ul class="navbar-nav flex-row nav-justified align-items-center w-100 text-center">
                <li class="nav-item">
                    <NavLink class="nav-link" href="ispezioni" Match="NavLinkMatch.All">
                        <div class="d-flex flex-column">
                            <i class="ri-file-list-3-line"></i>
                            <span>Ispezioni</span>
                        </div>
                    </NavLink>
                </li>
                <li class="nav-item">
                    <NavLink class="nav-link" href="user" Match="NavLinkMatch.All">
                        <div class="d-flex flex-column">
                            <i class="ri-user-line"></i>
                            <span>Profilo</span>
                        </div>
                    </NavLink>
                </li>
            </ul>
        </div>

        @if (PlusVisible)
        {
            <MudFabMenu ButtonClass="custom-plus-button" MenuClass="custom-menu-fab" OnClick="@OnOpenMenu"
                        StartIcon="@Icons.Material.Filled.Add"
                        IconColor="Color.Primary" Color="Color.Surface" AlignItems="AlignItems.End"
                        Size="Size.Medium" IconSize="Size.Medium">
                @if (SchedaVisible)
                {
                    @if (!_isCompleted)
                    {
                        <MudFabMenuItem Disabled="!NetworkService.IsNetworkAvailable()" OnClick="@NewScheda"
                                        Label="Nuova scheda" Color="Color.Surface"/>
                    }

                    <MudFabMenuItem Disabled="!NetworkService.IsNetworkAvailable()" OnClick="@DeleteInspection"
                                    Label="Cancella ispezione" Color="Color.Surface"/>

                    if (ShowCompleteInspection)
                    {
                        <MudFabMenuItem Disabled="!NetworkService.IsNetworkAvailable()" OnClick="@CompleteInspection"
                                        Label="Concludi ispezione" Color="Color.Surface"/>
                    }
                }
                else
                {
                    <MudFabMenuItem Disabled="!NetworkService.IsNetworkAvailable()" OnClick="@NewInspection"
                                    Label="Nuova ispezione" Color="Color.Surface"/>
                }
            </MudFabMenu>
        }
    </nav>
</div>

<ConfirmMessageBox @ref="_messageBox" NoText="No" YesText="Si" YesColor="Color.Primary"
                   Message="Completando l'ispezione non sarà più possibile editarla o aggiungere ulteriori segnalazioni. Procedere?"/>

@code
{
    private bool IsVisible { get; set; } = true;
    private bool PlusVisible { get; set; } = true;
    private bool ShowCompleteInspection { get; set; }
    private bool SchedaVisible { get; set; }
    private bool _isCompleted;

    private ConfirmMessageBox _messageBox = null!;

    protected override Task OnInitializedAsync()
    {
        NavigationManager.LocationChanged += (_, args) =>
        {
            var location = args.Location.Remove(0, NavigationManager.BaseUri.Length);

            var newIsVisible = new List<string> { "ispezioni", "ispezione", "user" }
                .Contains(location);

            var newPlusVisible = new List<string> { "ispezioni", "ispezione", "user" }
                .Contains(location);

            if (IsVisible == newIsVisible && PlusVisible == newPlusVisible) return;

            IsVisible = newIsVisible;
            PlusVisible = newPlusVisible;

            if (location.EqualsIgnoreCase("ispezione"))
            {
                var ispezione = SteupDataService.InspectionPageState.Ispezione;
                if (ispezione.Stato == StatusEnum.Completata) PlusVisible = false;
            }

            StateHasChanged();
        };
        return Task.CompletedTask;
    }

    private async Task NewInspection()
    {
        if (await SteupDataService.CanOpenNewInspection())
        {
            _ = Dialog.OpenSelectShop();
        }
        else
        {
            await Dialog.ShowWarning("Per aprire una nuova ispezione è necessario concludere prima tutte le ispezioni aperte più vecchie di 20 giorni!");
        }
    }

    private async Task CompleteInspection()
    {
        var result = await _messageBox.ShowAsync();

        if (result is true)
            Messenger.Send(new CompleteInspectionMessage());
    }

    private async Task NewScheda()
    {
        var ispezione = SteupDataService.InspectionPageState.Ispezione;
        var modal = await Dialog.OpenFormScheda(ispezione.CodMdep, ispezione.Data, true);

        if (modal is { Canceled: false })
            Messenger.Send(new NewSchedaMessage());
    }

    private void OnOpenMenu()
    {
        var location = NavigationManager.Uri.Remove(0, NavigationManager.BaseUri.Length);

        SchedaVisible = new List<string> { "ispezione" }.Contains(location);

        var ispezione = SteupDataService.InspectionPageState.Ispezione;
        _isCompleted = ispezione.Stato == StatusEnum.Completata;
        // Concludi non ha senso su un'ispezione gia completata
        ShowCompleteInspection = !ispezione.ActivityId.IsNullOrEmpty() && !_isCompleted;
        StateHasChanged();
    }

    private async Task DeleteInspection()
    {
        try
        {
            var ispezione = SteupDataService.InspectionPageState.Ispezione;
            await IspezioniService.DeleteIspezioneAsync(ispezione.CodMdep, ispezione.Data, ispezione.Rilevatore);
            
            await Js.InvokeVoidAsync("goBack");
        }
        catch (Exception e)
        {
            await Dialog.ShowError(e.Message);
        }
    }
}