@page "/User/{CodContact}/{IsContact:bool}"
@attribute [Authorize]
@using AutoMapper
@using salesbook.Shared.Components.Layout
@using salesbook.Shared.Core.Entity
@using salesbook.Shared.Core.Interface
@using salesbook.Shared.Components.Layout.Spinner
@using salesbook.Shared.Core.Dto
@using salesbook.Shared.Components.SingleElements
@inject IManageDataService ManageData
@inject IMapper Mapper
@inject IDialogService Dialog
@inject INetworkService NetworkService

<HeaderLayout BackTo="Indietro" LabelSave="Modifica" OnSave="() => OpenUserForm(Anag)" Back="true" BackOnTop="true" Title="" ShowProfile="false" />

@if (IsLoading)
{
    <SpinnerLayout FullScreen="true"/>
}
else
{
    <div class="container content">
        <div class="container-primary-info">
            <div class="section-primary-info">
                <MudAvatar Style="height: 70px; width: 70px; font-size: 2rem; font-weight: bold" Color="Color.Secondary">
                    @UtilityString.ExtractInitials(Anag.RagSoc)
                </MudAvatar>

                <div class="personal-info">
                    <span class="info-nome">@Anag.RagSoc</span>
                    @if (Anag.Indirizzo != null)
                    {
                        <span class="info-section">@Anag.Indirizzo</span>
                    }
                    @if (Anag is { Citta: not null, Cap: not null, Prov: not null })
                    {
                        <span class="info-section">@($"{Anag.Cap} - {Anag.Citta} ({Anag.Prov})")</span>
                    }
                </div>
            </div>

            <div class="divider"></div>

            <div class="section-info">
                <div class="section-personal-info">
                    @if (!string.IsNullOrEmpty(Anag.Telefono))
                    {
                        <div>
                            <span class="info-title">Telefono</span>
                            <span class="info-text">
                                @Anag.Telefono
                            </span>
                        </div>
                    }

                    @if (!string.IsNullOrEmpty(Anag.PartIva))
                    {
                        <div>
                            <span class="info-title">P. IVA</span>
                            <span class="info-text">
                                @Anag.PartIva
                            </span>
                        </div>
                    }
                </div>

                <div class="section-personal-info">
                    @if (!string.IsNullOrEmpty(Anag.EMail))
                    {
                        <div>
                            <span class="info-title">E-mail</span>
                            <span class="info-text">
                                @Anag.EMail
                            </span>
                        </div>
                    }

                    @if (Agente != null)
                    {
                        <div>
                            <span class="info-title">Agente</span>
                            <span class="info-text">
                                @Agente.FullName
                            </span>
                        </div>
                    }
                </div>
            </div>
        </div>

        <MudTabs TabPanelClass="custom-tab-panel" Elevation="2" Rounded="true" PanelClass="pt-2" Centered="true">
            <MudTabPanel Text="Contatti">
                @if (PersRif is { Count: > 0 })
                {
                    <div style="margin-top: 1rem;" class="container-pers-rif">
                        <Virtualize Items="PersRif" Context="person">
                            @{
                                var index = PersRif.IndexOf(person);
                                var isLast = index == PersRif.Count - 1;
                            }
                            <ContactCard Contact="person"/>
                            @if (!isLast)
                            {
                                <div class="divider"></div>
                            }
                        </Virtualize>
                    </div>
                }

                <div class="container-button">
                    <MudButton Class="button-settings infoText"
                               FullWidth="true"
                               Size="Size.Medium"
                               OnClick="OpenPersRifForm"
                               Variant="Variant.Outlined">
                        Aggiungi contatto
                    </MudButton>
                </div>
            </MudTabPanel>
            <MudTabPanel Text="Commesse">
                @if (Commesse.IsNullOrEmpty())
                {
                    <NoDataAvailable Text="Nessuna commessa presente"/>
                }
                else
                {
                    <Virtualize Items="Commesse" Context="commessa">
                        <CommessaCard Commessa="commessa"/>
                    </Virtualize>
                }
            </MudTabPanel>
        </MudTabs>
    </div>
}

@code {
    [Parameter] public string CodContact { get; set; }
    [Parameter] public bool IsContact { get; set; }

    private ContactDTO Anag { get; set; } = new();
    private List<PersRifDTO>? PersRif { get; set; }
    private List<JtbComt> Commesse { get; set; }
    private StbUser? Agente { get; set; }

    private bool IsLoading { get; set; } = true;

    protected override async Task OnInitializedAsync()
    {
        await LoadData();
    }

    private async Task LoadData()
    {
        if (IsContact)
        {
            var clie = (await ManageData.GetTable<AnagClie>(x => x.CodAnag.Equals(CodContact))).Last();
            Anag = Mapper.Map<ContactDTO>(clie);
        }
        else
        {
            var pros = (await ManageData.GetTable<PtbPros>(x => x.CodPpro.Equals(CodContact))).Last();
            Anag = Mapper.Map<ContactDTO>(pros);
        }

        await LoadPersRif();

        Commesse = await ManageData.GetTable<JtbComt>(x => x.CodAnag != null && x.CodAnag.Equals(CodContact));

        if (Anag.CodVage != null)
        {
            Agente = (await ManageData.GetTable<StbUser>(x => x.UserCode != null && x.UserCode.Equals(Anag.CodVage))).LastOrDefault();
        }

        IsLoading = false;
        StateHasChanged();
    }

    private async Task LoadPersRif()
    {
        if (IsContact)
        {
            var pers = await ManageData.GetTable<VtbCliePersRif>(x => x.CodAnag.Equals(Anag.CodContact));
            PersRif = Mapper.Map<List<PersRifDTO>>(pers);
        }
        else
        {
            var pers = await ManageData.GetTable<PtbProsRif>(x => x.CodPpro.Equals(Anag.CodContact));
            PersRif = Mapper.Map<List<PersRifDTO>>(pers);
        }
    }

    private async Task OpenPersRifForm()
    {
        var result = await ModalHelpers.OpenPersRifForm(Dialog, null, Anag, PersRif);

        if (result is { Canceled: false, Data: not null } && result.Data.GetType() == typeof(PersRifDTO))
        {
            await LoadPersRif();
        }
    }

    private async Task OpenUserForm(ContactDTO anag)
    {
        var result = await ModalHelpers.OpenUserForm(Dialog, anag);
    }

}