@using salesbook.Shared.Core.Dto
@using salesbook.Shared.Components.Layout
@using salesbook.Shared.Core.Interface
@using salesbook.Shared.Components.Layout.Overlay
@using salesbook.Shared.Core.Interface.IntegryApi
@using salesbook.Shared.Core.Interface.System.Network
@inject IManageDataService ManageData
@inject INetworkService NetworkService
@inject IIntegryApiService IntegryApiService

<MudDialog Class="customDialog-form">
    <DialogContent>
        <HeaderLayout ShowProfile="false" Cancel="true" OnCancel="() => MudDialog.Cancel()" LabelSave="@LabelSave" OnSave="Save" Title="@(IsNew ? "Nuovo" : "")" />

        <div class="content">
            <div class="input-card">
                <MudTextField ReadOnly="IsView" 
                              T="string?" 
                              Placeholder="Cognome e Nome"
                              Variant="Variant.Text"
                              Lines="1"
                              @bind-Value="PersRifModel.PersonaRif"
                              @bind-Value:after="OnAfterChangeValue"
                              DebounceInterval="500"
                              OnDebounceIntervalElapsed="OnAfterChangeValue"/>
            </div>

            <div class="input-card">
                <MudTextField ReadOnly="IsView"
                              T="string?"
                              Placeholder="Mansione"
                              Variant="Variant.Text"
                              Lines="1"
                              @bind-Value="PersRifModel.Mansione"
                              @bind-Value:after="OnAfterChangeValue"
                              DebounceInterval="500"
                              OnDebounceIntervalElapsed="OnAfterChangeValue" />
            </div>

            <div class="input-card">
                <div class="form-container">
                    <span class="disable-full-width">Email</span>

                    <MudTextField ReadOnly="IsView"
                                  T="string?"
                                  Variant="Variant.Text"
                                  FullWidth="true"
                                  Class="customIcon-select"
                                  Lines="1"
                                  @bind-Value="PersRifModel.EMail"
                                  @bind-Value:after="OnAfterChangeValue"
                                  DebounceInterval="500"
                                  OnDebounceIntervalElapsed="OnAfterChangeValue"/>
                </div>
                
                <div class="divider"></div>

                <div class="form-container">
                    <span class="disable-full-width">Fax</span>

                    <MudTextField ReadOnly="IsView"
                                  T="string?"
                                  Variant="Variant.Text"
                                  FullWidth="true"
                                  Class="customIcon-select"
                                  Lines="1"
                                  @bind-Value="PersRifModel.Fax"
                                  @bind-Value:after="OnAfterChangeValue"
                                  DebounceInterval="500"
                                  OnDebounceIntervalElapsed="OnAfterChangeValue"/>
                </div>
                
                <div class="divider"></div>

                <div class="form-container">
                    <span class="disable-full-width">Cellulare</span>

                    <MudTextField ReadOnly="IsView"
                                  T="string?"
                                  Variant="Variant.Text"
                                  FullWidth="true"
                                  Class="customIcon-select"
                                  Lines="1"
                                  @bind-Value="PersRifModel.NumCellulare"
                                  @bind-Value:after="OnAfterChangeValue"
                                  DebounceInterval="500"
                                  OnDebounceIntervalElapsed="OnAfterChangeValue"/>
                </div>
                
                <div class="divider"></div>
                
                <div class="form-container">
                    <span class="disable-full-width">Telefono</span>

                    <MudTextField ReadOnly="IsView"
                                  T="string?"
                                  Variant="Variant.Text"
                                  FullWidth="true"
                                  Class="customIcon-select"
                                  Lines="1"
                                  @bind-Value="PersRifModel.Telefono"
                                  @bind-Value:after="OnAfterChangeValue"
                                  DebounceInterval="500"
                                  OnDebounceIntervalElapsed="OnAfterChangeValue" />
                </div>
            </div>
        </div>
    </DialogContent>
</MudDialog>

<SaveOverlay VisibleOverlay="VisibleOverlay" SuccessAnimation="SuccessAnimation"/>

@code {
    [CascadingParameter] private IMudDialogInstance MudDialog { get; set; }

    [Parameter] public PersRifDTO? OriginalModel { get; set; }
    [Parameter] public ContactDTO? ContactModel { get; set; }
    [Parameter] public List<PersRifDTO>? PersRifList { get; set; }

    private PersRifDTO PersRifModel { get; set; } = new();

    private bool IsNew => OriginalModel is null;
    private bool IsView => !NetworkService.ConnectionAvailable;

    private string? LabelSave { get; set; }

    //Overlay for save
    private bool VisibleOverlay { get; set; }
    private bool SuccessAnimation { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Snackbar.Configuration.PositionClass = Defaults.Classes.Position.TopCenter;

        _ = LoadData();

        LabelSave = IsNew ? "Aggiungi" : null;
    }

    private async Task Save()
    {
        VisibleOverlay = true;
        StateHasChanged();

        if (ContactModel != null && PersRifList != null)
        {
            PersRifList.Add(PersRifModel);

            var requestDto = new CRMCreateContactRequestDTO
            {
                TipoAnag = ContactModel.IsContact ? "C" : "P",
                Cliente = ContactModel,
                PersRif = PersRifList,
                CodVage = ContactModel.CodVage,
                CodAnag = ContactModel.CodContact
            };

            var response = await IntegryApiService.SaveContact(requestDto);

            switch (response)
            {
                case null:
                    VisibleOverlay = false;
                    StateHasChanged();
                    return;
                case {AnagClie: null, PtbPros: not null}:
                    await ManageData.InsertOrUpdate(response.PtbPros);
                    await ManageData.InsertOrUpdate(response.PtbProsRif);
                    break;
                case { AnagClie: not null, PtbPros: null }:
                    await ManageData.InsertOrUpdate(response.AnagClie);
                    await ManageData.InsertOrUpdate(response.VtbCliePersRif);
                    break;
                default:
                    VisibleOverlay = false;
                    StateHasChanged();
                    return;
            }
        }

        SuccessAnimation = true;
        StateHasChanged();

        await Task.Delay(1250);

        MudDialog.Close(PersRifModel);
    }

    private async Task LoadData()
    {
        if (!IsNew)
            PersRifModel = OriginalModel!.Clone();
    }

    private void OnAfterChangeValue()
    {
        if (!IsNew)
        {
            LabelSave = !OriginalModel.Equals(PersRifModel) ? "Aggiorna" : null;
        }
    }
}