@using salesbook.Shared.Core.Dto.JobProgress
@using salesbook.Shared.Core.Dto.PageState
@using salesbook.Shared.Core.Entity
@inject JobSteps JobSteps

<div @onclick="OpenPageCommessa" class="activity-card">
    <div class="activity-left-section">
        <div class="activity-body-section">
            <div class="title-section">
                <MudText Class="activity-title" Typo="Typo.body1" HtmlTag="h3">@Commessa.CodJcom</MudText>
                <div class="activity-hours-section">
                    @if (LastUpd is not null)
                    {
                        <span class="activity-hours">Aggiornato il @($"{LastUpd:d}")</span>
                    }
                </div>
            </div>
            <span class="activity-title">@Commessa.Descrizione</span>
        </div>
    </div>

    <div class="activity-info-section">
        @if (Stato is not null)
        {
            <MudChip T="string" Variant="Variant.Outlined" Icon="@IconConstants.Chip.Stato" Size="Size.Small">@Stato</MudChip>
        }
    </div>
</div>

@code {
    [Parameter] public JtbComt Commessa { get; set; } = new();
    [Parameter] public string RagSoc { get; set; } = "";
    [Parameter] public List<CRMJobStepDTO>? Steps { get; set; }

    private string? Stato { get; set; }
    private DateTime? LastUpd { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        GetStepInfo();
    }

    private void GetStepInfo()
    {
        if (Steps is null) return;

        // Ultimo step non skip
        var lastBeforeSkip = Steps
            .LastOrDefault(s => s.Status is { Skip: false });

        if (lastBeforeSkip is not null)
            Stato = lastBeforeSkip.StepName;

        // Ultima data disponibile
        LastUpd = Steps
            .Where(s => s.Date.HasValue)
            .Select(s => s.Date!.Value)
            .DefaultIfEmpty()
            .Max();

        if (LastUpd.Equals(DateTime.MinValue))
            LastUpd = null;
    }


    private void OpenPageCommessa()
    {
        JobSteps.Steps = Steps;
        NavigationManager.NavigateTo($"commessa/{Commessa.CodJcom}/{RagSoc}");
    }

}