@page "/ispezione"
@using Microsoft.Extensions.Logging
@using SteUp.Shared.Components.Layout
@using SteUp.Shared.Components.Layout.Overlay
@using SteUp.Shared.Components.SingleElements.Card
@using SteUp.Shared.Core.Dto
@using SteUp.Shared.Core.Entities
@using SteUp.Shared.Core.Enum
@using SteUp.Shared.Core.Interface.IntegryApi
@using SteUp.Shared.Core.Interface.LocalDb
@using SteUp.Shared.Core.Interface.System
@using SteUp.Shared.Core.Messages.Ispezione
@using SteUp.Shared.Core.Messages.Scheda
@inject NewSchedaService NewScheda
@inject CompleteInspectionService CompleteInspection
@inject IIspezioniService IspezioniService
@inject IDialogService Dialog
@inject IIntegrySteupService IntegrySteupService
@inject IFileManager FileManager
@inject ILogger<IspezionePage> Logger
@implements IDisposable

<HeaderLayout Title="Ispezione" BackTo="Indietro" Back="true"/>

<div class="container content pb-safe-area ispezione">
    <InspectionCard Ispezione="SteupDataService.InspectionPageState.Ispezione"/>

    @if (!SchedeGrouped.IsNullOrEmpty())
    {
        <MudExpansionPanels MultiExpansion="true">
            @foreach (var group in SchedeGrouped)
            {
                <MudExpansionPanel Class="expansion-panel" Expanded="true" Text="@group.Key.Descrizione">
                    <TitleContent>
                        <div class="header-scheda-group">
                            <div class="title">
                                <MudText Typo="Typo.h6"><b>@group.Key.Descrizione</b></MudText>
                                <MudChip T="string" Size="Size.Small" Color="Color.Default">
                                    @($"{group.Value.Count} sched{(group.Value.Count == 1 ? "a" : "e")}")
                                </MudChip>
                            </div>
                            @if (SteupDataService.InspectionPageState.Ispezione.Stato != StatusEnum.Completata)
                            {
                                <div class="action-scheda-group">
                                    @if (NetworkService.IsNetworkAvailable())
                                    {
                                        <MudFab StartIcon="@Icons.Material.Rounded.Add"
                                                Color="Color.Warning" Size="Size.Small"
                                                OnClick="@(() => CreateNewScheda(group.Key))"/>

                                        <MudFab StartIcon="@Icons.Material.Rounded.CloudSync" Label="Esporta reparto"
                                                Color="Color.Success" Size="Size.Small"
                                                OnClick="@(() => ExportReparto(group.Key))"/>
                                    }
                                    else
                                    {
                                        <MudFab StartIcon="@Icons.Material.Rounded.Add"
                                                Label="@($"Nuova scheda su {group.Key.Descrizione}")"
                                                Color="Color.Warning" Size="Size.Medium"
                                                OnClick="@(() => CreateNewScheda(group.Key))"/>
                                    }
                                </div>
                            }
                        </div>
                    </TitleContent>
                    <ChildContent>
                        @foreach (var scheda in group.Value)
                        {
                            <SchedaCard Scheda="scheda" OnSchedaDeleted="OnSchedaDeleted"
                                        OnSchedaModified="OnSchedaModified"
                                        Ispezione="@SteupDataService.InspectionPageState.Ispezione"/>
                        }
                    </ChildContent>
                </MudExpansionPanel>
            }
        </MudExpansionPanels>
    }
</div>

<SpinnerOverlay VisibleOverlay="VisibleOverlay"/>

@code {
    private List<Scheda> SchedeList { get; set; } = [];
    private Dictionary<JtbFasiDto, List<Scheda>> SchedeGrouped { get; set; } = [];

    private bool VisibleOverlay { get; set; }

    protected override void OnInitialized()
    {
        NewScheda.OnNewScheda += LoadSchede;
        CompleteInspection.OnComplete += HandleCompleteInspection;

        LoadSchede();
    }

    private void LoadSchede()
    {
        var ispezione = SteupDataService.InspectionPageState.Ispezione;

        InvokeAsync(async () =>
        {
            SchedeList = await IspezioniService.GetAllSchedeOfIspezioneAsync(
                ispezione.CodMdep, ispezione.Data, ispezione.Rilevatore
            );

            GroupSchede();
            StateHasChanged();
        });
    }

    private async void HandleCompleteInspection()
    {
        try
        {
            await InvokeAsync(() =>
            {
                VisibleOverlay = true;
                StateHasChanged();
            });

            var ispezione = SteupDataService.InspectionPageState.Ispezione;

            foreach (var scheda in ispezione.Schede.Where(x => x.ActivityId == null))
            {
                var apiResponse = await IntegrySteupService.SaveScheda(
                    new SaveRequestDto
                    {
                        LocalIdScheda = scheda.Id,
                        ActivityTypeId = scheda.ActivityTypeId,
                        CodJfas = scheda.CodJfas,
                        CodMdep = ispezione.CodMdep,
                        DataCreazione = ispezione.Data,
                        Note = scheda.Note,
                        PersonaRif = scheda.Responsabile,
                        Barcodes = scheda.Articoli.ConvertAll(x => x.Barcode),
                        Scandeza = (ScadenzaEnum)scheda.Scadenza,
                        ParentActivityId = scheda.Ispezione?.ActivityId
                    }
                );

                if (apiResponse == null) continue;

                scheda.ActivityId = apiResponse.ActivityIdScheda;
                await IspezioniService.UpdateSchedaAsync(scheda);

                await IspezioniService.UpdateActivityIdIspezioneAsync(
                    ispezione.CodMdep,
                    ispezione.Data,
                    ispezione.Rilevatore,
                    apiResponse.ActivityIdIspezione
                );
                
                if (scheda.ImageNames == null) continue;
                
                var fileList = (await FileManager.GetInspectionFiles(ispezione, scheda.ImageNames))?
                    .Where(x => x.ToUpload).ToList();

                if (fileList == null) continue;

                foreach (var file in fileList)
                {
                    await IntegrySteupService.UploadFile(scheda.ActivityId!, file.FileBytes!, file.Name!);
                }
            }

            await IntegrySteupService.CompleteInspection(ispezione.ActivityId!);
            await IspezioniService.UpdateStatoIspezioneAsync(
                ispezione.CodMdep,
                ispezione.Data,
                ispezione.Rilevatore,
                StatusEnum.Completata
            );
            
            SteupDataService.InspectionPageState.Ispezione.Stato = StatusEnum.Completata;

            await InvokeAsync(() =>
            {
                VisibleOverlay = false;
                StateHasChanged();
            });
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);

            await InvokeAsync(() =>
            {
                VisibleOverlay = false;
                StateHasChanged();
            });

            OnError(e, e.Message);
        }
    }

    private void GroupSchede()
    {
        SchedeGrouped = SchedeList
            .Where(s => s.Reparto != null)
            .GroupBy(s => s.CodJfas)
            .ToDictionary(
                g => g.First().Reparto!,
                g => g.ToList()
            );
    }

    private void OnSchedaModified(Scheda obj)
    {
        var index = SchedeList.FindIndex(x => x.Id.Equals(obj.Id));
        if (index > 0) SchedeList[index] = obj;

        GroupSchede();
        StateHasChanged();
    }

    private void OnSchedaDeleted(Scheda obj)
    {
        SchedeList.Remove(obj);
        GroupSchede();
        StateHasChanged();
    }

    private async Task CreateNewScheda(JtbFasiDto jtbFasi)
    {
        var modal = await Dialog.OpenFormScheda(
            SteupDataService.InspectionPageState.Ispezione.CodMdep,
            SteupDataService.InspectionPageState.Ispezione.Data,
            true,
            new Scheda { Reparto = jtbFasi }
        );

        if (modal is { Canceled: false }) LoadSchede();
    }

    private async Task ExportReparto(JtbFasiDto jtbFasi)
    {
        VisibleOverlay = true;
        StateHasChanged();

        var ispezione = SteupDataService.InspectionPageState.Ispezione;

        var saveRequest = SchedeGrouped[jtbFasi].ConvertAll(x =>
        {
            return new SaveRequestDto
            {
                LocalIdScheda = x.Id,
                ActivityTypeId = x.ActivityTypeId,
                CodJfas = x.CodJfas,
                CodMdep = ispezione.CodMdep,
                DataCreazione = ispezione.Data,
                Note = x.Note,
                PersonaRif = x.Responsabile,
                Barcodes = x.Articoli.ConvertAll(y => y.Barcode),
                Scandeza = (ScadenzaEnum)x.Scadenza,
                ParentActivityId = x.Ispezione?.ActivityId
            };
        });

        var apiResponse = await IntegrySteupService.SaveMultipleSchede(saveRequest);

        if (apiResponse != null)
        {
            SteupDataService.InspectionPageState.Ispezione.ActivityId = apiResponse.ActivityIdIspezione;

            await IspezioniService.UpdateActivityIdIspezioneAsync(ispezione.CodMdep, ispezione.Data,
                UserSession.User.Username, apiResponse.ActivityIdIspezione
            );

            if (apiResponse.ActivityIdSchedaList.IsNullOrEmpty()) return;

            foreach (var scheda in SchedeGrouped[jtbFasi])
            {
                scheda.ActivityId = apiResponse.ActivityIdScheda;
                await IspezioniService.UpdateActivityIdSchedaAsync(scheda.Id, scheda.ActivityId);

                var activityId = apiResponse.ActivityIdSchedaList!.Find(x =>
                    x.LocalId != null && x.LocalId == scheda.Id
                )?.ActivityId;

                if (activityId == null) return;

                scheda.ActivityId = activityId;
                await IspezioniService.UpdateActivityIdSchedaAsync(scheda.Id, scheda.ActivityId);
            }
        }

        VisibleOverlay = false;
        StateHasChanged();
    }

    private void OnError(Exception?  e, string? errorMessage)
    {
        if (e != null) Logger.LogError(e, errorMessage);
        if (errorMessage == null) return;

        _ = Dialog.ShowError(errorMessage);
    }

    void IDisposable.Dispose()
    {
        NewScheda.OnNewScheda -= LoadSchede;
        CompleteInspection.OnComplete -= HandleCompleteInspection;
    }

}