@page "/mailsendrelance_edit/{id}"
@inject ReAct_PME.WebUI.ServicesUI.ApiService ApiService
@inject ReAct_PME.WebUI.ServicesUI.AuthService AuthService
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager Navigation
@inject IToastService ToastService
@inject Blazored.LocalStorage.ILocalStorageService localStorage
@inject HttpClient Http
@using Blazored.Toast.Configuration;
@using Blazored.Toast.Services;
@using Microsoft.AspNetCore.Components.Authorization;

@if (SelectedItem != null)
{
    titre = $"{SelectedItem!.Subject}";
}

<h2 class="text-center" style="font-weight:bold">@titre</h2>


@if (SelectedItem == null)
{
    <p>Chargement...</p>
}
else
{
    <div>
        <div class="email-header">

            <!-- Ligne 1 : Nom + Catégorie -->
            <div class="d-flex justify-content-between align-items-center">
                <div class="fw-bold">@MessageOrigineRelance!.ToSTR</div>
                <span class="badge bg-primary"></span>
            </div>

            <!-- Ligne 2 : Adresse mail + Priorités -->
            <div class="d-flex justify-content-between align-items-center">
                <div class="text-muted small">@MessageOrigineRelance!.DateSTR</div>

            </div>
        </div>

        <!-- Ligne 3 : message d'origine -->
        <div class="email-footer mt-3 d-flex justify-content-between">
            <button class="@(Expanded_MSG_ORIGINE ? "collapsibleexpanded" : "collapsible")" @onclick="() => Toggle(1)">
                Message d'origine :
            </button>
        </div>

        <div class="contentinfo" style="display:@(Expanded_MSG_ORIGINE ? "block" : "none")">
            <textarea id="TXT_MSG_ORIGINE"
                      @bind="@MessageOrigineRelance.Body"
                      @oninput="@(() => AdjustHeight("TXT_MSG_ORIGINE"))"
                      class="form-control auto-resize-textarea"
                      readonly />
        </div>

        <div class="email-footer mt-3 d-flex justify-content-between">
            <button class="@(Expanded_RELANCE ? "collapsibleexpanded" : "collapsible")" @onclick="() => Toggle(2)">
                Relance :
            </button>
        </div>
        <div class="contentinfo" style="display:@(Expanded_RELANCE ? "block" : "none")">
            <textarea id="TXT_RELANCE"
                      @bind="@SelectedItem.FollowUpDraft"
                      @oninput="@(() => AdjustHeight("TXT_RELANCE"))"
                      rows="10"
                      class="form-control auto-resize-textarea"
                      />
        </div>

        <br />
        <div class="form-group row">
            <div class="col-sm-10 offset-sm-2">
                <button type="button" class="btn btn-outline-light me-2" @onclick="SendReponse">Envoyer la relance</button>

                <button type="button" class="btn btn-outline-light me-2" @onclick="GenerateAgain">Re-générer la relance</button>

                <button type="button" class="btn btn-outline-light" @onclick="Cancel">Fermer</button>
            </div>
        </div>
    </div>
}

@code {
    [Parameter] public string Id { get; set; } = "";
    [CascadingParameter] public IModalService Modal { get; set; } = default!;

    private bool Expanded_MSG_ORIGINE = false;
    private bool Expanded_RELANCE = false;

    public Services.ThreadItem SelectedItem { get; set; } = new();
    public Services.MailMessageItem? MessageOrigineRelance { get; set; } = new();

    private string titre = "Relance";
    private List<Paragraphe> Paragraphes = new();
    private class Paragraphe
    {
        public int Id { get; set; }
        public string Title { get; set; } = "";
        public string Text { get; set; } = "";
        public bool Expanded { get; set; } = false;
        public string UidString { get; set; } = "";

    }


    #region Rendre les zones extensibles
    [Inject] IJSRuntime? JS { get; set; }

    private async Task AdjustHeight(string id)
    {
        await JS.InvokeVoidAsync("resizeTextarea", id);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        // Ajuste la hauteur une première fois quand le textarea est initialisé
        await JS.InvokeVoidAsync("resizeTextarea", "TXT_MSG_ORIGINE");
        await JS.InvokeVoidAsync("resizeTextarea", "TXT_RELANCE");
    }

    #endregion


    private void Toggle(int id)
    {
        if(id == 1)
        {
            Expanded_MSG_ORIGINE = !Expanded_MSG_ORIGINE;
        }
        else
        {
            Expanded_RELANCE = !Expanded_RELANCE;
        }
    }



    protected override async Task OnInitializedAsync()
    {
        #region Vérification si utilisateur est connecté et s''il a les droits
        /*
        Dans notre cas présent, il n'y a pas de sécurité
                    var tok = PagesInitializer.VerifConnexionAndRules(AuthenticationStateProvider, Navigation, Http, ToastService, "api/LOGS_DTO");
        if (tok == null || tok.Length == 0)
            return;
        else
            AuthService.SetToken(tok);
        */
        #endregion

        #region Chargement des listes
                                // Si pas de sécurité ou profil Admin --> on montre tout
                                // Sinon selon la customisation de Repository

        #endregion


                                var selectedItem = await ApiService!.GetByIdAsync<Services.ThreadItem>($"api/ListeMails/send/{Id}");
        if (selectedItem != null)
        {
            SelectedItem = selectedItem;
            MessageOrigineRelance = SelectedItem!.Messages.Where(m => m.Id == SelectedItem.LastFollowUpForMessageId).FirstOrDefault();
        }
    }
    
    private async Task SendReponse()
    {
        if (SelectedItem != null)
        {

            try
            {
                bool b = true;//await ApiService.UpdateAsync($"api/LOGS_DTO/{Id}", item);
                if (b)
                {
                    ToastService.ShowSuccess("Envoi réussi !", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
                    await Task.Delay(2000);
                    Navigation.NavigateTo("/listemails_card", forceLoad: true);
                }
                else
                {
                    ToastService.ShowError($"Erreur : Echec de l'envoi.", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
                }
            }
            catch (Exception ex)
            {
                ToastService.ShowError($"Erreur : {ex.Message}", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
            }
        }
    }

    private void Cancel()
    {
        Navigation.NavigateTo("/listemailssend_card");
    }

    private async Task LoadEmailAsync(string uid)
    {
        var selectedItem = await ApiService!.GetByIdAsync<Services.ThreadItem>($"api/ListeMails/send/{Id}");
        if (selectedItem != null)
        {
            SelectedItem = selectedItem;
            MessageOrigineRelance = SelectedItem!.Messages.Where(m => m.Id == SelectedItem.LastFollowUpForMessageId).FirstOrDefault();
        }


    }

    private async Task GenerateAgain()
    {
        var context = new List<ContextGeneration>();
        context.Add(new ContextGeneration { Name = "Type de mail", Description = "Relance" });
        /*
        context.Add(new ContextGeneration { Name = "Contenu du mail reçu", Description = Email!.TextBody });
        context.Add(new ContextGeneration { Name = "Catégorie du mail", Description = Email!.Categorie });
        context.Add(new ContextGeneration { Name = "Stratégie de réponse", Description = Email!.Strategie });
        */

                                var parameters = new ModalParameters()
                                    .Add("ReponseOld", SelectedItem.FollowUpDraft)
                                    .Add("Context", context);

        var options = new ModalOptions
        {
            DisableBackgroundCancel = true,
            Position = ModalPosition.TopCenter,
            UseCustomLayout = true
        };

        var modal = Modal.Show<_ModelGenerateAgain>(("Nouvelle génération").ToUpper(), parameters, options);
        var result = await modal.Result;


        if (result.Cancelled)
        {
            ToastService.ShowWarning("La modale a été annulée.", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
        }
        else if (result.Confirmed)
        {
            var nouvelleReponse = result.Data as string;
            SelectedItem.FollowUpDraft = nouvelleReponse!;

            // Enregistrer la réponse (Endpoint vers EmailService.SauvegarderReponseEmails())
            var mini = new Services.ThreadItemMini();
            mini.Id = SelectedItem.Id;
            mini.FollowUpDraft = SelectedItem.FollowUpDraft;
            var b = await ApiService.SauvegardeItem<Services.ThreadItemMini>($"api/ListeMails/sendsaveitem", mini!);
            if (b)
            {
                // + Afficher la nouvelle réponse (redirection vers "/mail_edit/{Email.id}")
                //Navigation.NavigateTo($"/mail_edit/{Email!.UidString}", forceLoad: true);
                await LoadEmailAsync(SelectedItem.Id!);
                StateHasChanged();
            }


        }



    }
}

