@page "/mailsend_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 (Conversation != null)
{
    titre = $"{Conversation!.Subject}";
}

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


@if (Conversation == null)
{
    <p>Chargement...</p>
}
else
{
    <div>
        <div class="conversation-container">
            @foreach (var msg in Conversation.Messages)
            {
                var textareaId = $"TEXT_{msg.Id}";

                if (msg.Direction == "in")  
                {
                    <div class="message message-incoming">
                        <div class="meta">
                            <div class="meta-item">@msg.SubjectSTR</div>
                            <div class="meta-item">@msg.FolderSTR</div>
                            <div class="meta-item">@msg.FromSTR</div>
                            <div class="meta-item">@msg.ToSTR</div>
                            <div class="meta-item">@msg.DateSTR</div>
                        </div>
                        <div class="bubble incoming-bubble">
                            <textarea id="@textareaId"
                                      style="width:80vw; max-width:80%; min-width:80vw; background-color:sandybrown !important; color:black !important"
                                      @bind="msg.Body"
                                      @oninput="@(() => AdjustHeight($"{textareaId}"))"
                                      class="form-control auto-resize-textarea"
                                      readonly />
                        </div>
                    </div>
                }
                else  
                {
                    <div class="message message-outgoing">
                        <div class="meta">
                            <div class="meta-item">@msg.SubjectSTR</div>
                            <div class="meta-item">@msg.FolderSTR</div>
                            <div class="meta-item">@msg.FromSTR</div>
                            <div class="meta-item">@msg.ToSTR</div>
                            <div class="meta-item">@msg.DateSTR</div>
                        </div>
                        <div class="bubble outgoing-bubble">
                            <textarea id="@textareaId"
                                      style="width:80vw; max-width:80%; min-width:80vw; background-color:blue !important;"
                                      @bind="msg.Body"
                                      @oninput="@(() => AdjustHeight($"{textareaId}"))"
                                      class="form-control auto-resize-textarea"
                                      readonly />
                        </div>
                    </div>
                }
            }
        </div>

        <br />
        <div class="form-group row">
            <div class="message-outgoing" style="padding-right:35px">
                <button type="button" class="btn btn-outline-light" @onclick="Cancel">Fermer</button>
            </div>
        </div>
    </div>
}

@code {
    [Parameter] public string Id { get; set; } = "";

    private Services.ThreadItem? Conversation = new();
    private string titre = "Détail d'une conversation";

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

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

    #endregion

    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


                Conversation = await ApiService.GetByIdAsync<Services.ThreadItem>($"api/ListeMails/Send/{Id}");


    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        // Ajuste la hauteur une première fois quand le textarea est initialisé
        if (Conversation != null && Conversation.Messages.Count > 0)
        {
            foreach (var msg in Conversation.Messages)
            {
                var id = $"TEXT_{msg.Id}";
                await JS.InvokeVoidAsync("resizeTextarea", id);
            }
        }
    }

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

