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

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


@if (Email == 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">@Email.FromName</div>
                <span class="badge bg-primary">@Email.Categorie</span>
            </div>

            <!-- Ligne 2 : Adresse mail + Priorités -->
            <div class="d-flex justify-content-between align-items-center">
                <div class="text-muted small">@Email.From</div>
                <div class="priorite-badge">
                    @RenderPriorite()
                </div>
            </div>

            <!-- Ligne 3 : Date -->
            <div class="d-flex justify-content-between align-items-center">
                <div class="text-muted small">@Email.Date</div>
            </div>

            <!-- Ligne 4 : Pictogrammes + Analyse -->
            <div class="d-flex justify-content-between align-items-center">
                <div class="d-flex align-items-center gap-2">
                    <!-- Pictogramme destinataire -->
                    <div class="fw-bold" title="@Email.IsDestinatairePrincipal_STR_TXT">
                        @Email.IsDestinatairePrincipal_STR
                    </div>

                    <!-- Pictogramme présence suspecte -->
                    @if (Email.PresenceSuspecte)
                    {
                        <div class="fw-bold text-danger" title="Éléments suspects contenus dans l'email ou ses PJ">
                            @Email.PresenceSuspecte_STR
                        </div>
                    }

                    <!-- Pictogramme présence PJ -->
                    @if (Email.PJ_NBR > 0)
                    {
                        <div class="fw-bold text-danger" title="@($"{Email.PJ_NBR} pièce(s) jointe(s)")">
                            @Email.PJ_NBR_STR
                        </div>
                    }
                </div>

                <!-- Analyse -->
                <div class="rounded">
                    <span class="badge bg-light" style="color:@GetAnalyseColor();">
                        Analyse : @Email.Analyse
                    </span>
                </div>
            </div>
        </div>

        <!-- Autres lignes -->
        <div class="form-group row">
            <label for="TO" class="col-sm-2 col-form-label text-muted">Adressé à : </label>
            <div class="col-sm-10">
                <label id="TO" class="col-sm-10 col-form-label text-muted">@Email.To.Replace(";", " ; ")</label>
            </div>
        </div>

        @if (Email.Cc != "")
        {
            <div class="form-group row">
                <label for="CC" class="col-sm-2 col-form-label text-muted">Copie à : </label>
                <div class="col-sm-10">
                    <label id="CC" class="col-sm-10 col-form-label text-muted">@Email.Cc.Replace(";", " ; ")</label>
                </div>
            </div>
        }

        <!-- Les détails du mails -->
        @foreach (var item in Paragraphes)
        {
            if (item.Text.Trim() != "")
            {

                var textareaId = $"TEXT_{Email.UidString}_{item.Id}";

                <div class="email-footer mt-3 d-flex justify-content-between">
                    <button class="@(item.Expanded ? "collapsibleexpanded" : "collapsible")" @onclick="() => Toggle(item.Id)">
                        @item.Title :
                    </button>
                </div>

                <div class="contentinfo" style="display:@(item.Expanded ? "block" : "none")">
                    <textarea id="@textareaId"
                                @bind="item.Text"
                                @oninput="@(() => AdjustHeight($"{textareaId}"))"
                                class="form-control auto-resize-textarea"
                                readonly="@(item.Id != 4)" />
                </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 réponse</button>

                <button type="button" class="btn btn-outline-light me-2" @onclick="GenerateAgain">Re-générer la réponse</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 Services.EmailMessage? Email = new();
    private string titre = "Détail d'un Mail non lu";
    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; } = "";

    }

    private List<Paragraphe> GetParagraphes()
    {
        List<Paragraphe> lstParagrah = new();

        Paragraphe p0 = new();
        p0.Id = 0;
        p0.Title = "Contenu du mail";
        p0.Text = Email!.TextBody;
        p0.UidString = Email!.UidString!;

        Paragraphe p1 = new();
        p1.Id = 1;
        p1.Title = "Résumé";
        p1.Text = Email.Resume;
        p1.UidString = Email!.UidString!;

        Paragraphe p2 = new();
        p2.Id = 2;
        p2.Title = "Résumé des PJ";
        p2.Text = Email.ContentPJ_STR;
        p2.UidString = Email!.UidString!;

        Paragraphe p3 = new();
        p3.Id = 3;
        p3.Title = "Stratégie";
        p3.Text = Email.Strategie;
        p3.UidString = Email!.UidString!;

        Paragraphe p4 = new();
        p4.Id = 4;
        p4.Title = "Réponse proposée";
        p4.Text = Email.Reponse;
        p4.UidString = Email!.UidString!;

        lstParagrah.Add(p0);
        lstParagrah.Add(p1);
        lstParagrah.Add(p2);
        lstParagrah.Add(p3);
        lstParagrah.Add(p4);

        return lstParagrah;
    }

    #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é
        foreach (var p in Paragraphes)
        {
            var id = $"TEXT_{Email.UidString}_{p.Id}";
            await JS.InvokeVoidAsync("resizeTextarea", id);
        }

    }

    #endregion


    private void Toggle(int id)
    {
        var p = Paragraphes.FirstOrDefault(p => p.Id == id);
        if (p != null) p.Expanded = !p.Expanded;
    }

    private string GetAnalyseColor()
    {
        return Email!.Analyse switch
        {
            "Positif" => "green",
            "Négatif" => "red",
            "Neutre" => "orange",
            _ => "gray"
        };
    }

    private RenderFragment RenderPriorite() => builder =>
    {
        if (Email!.IsImportant && Email!.IsUrgent)
        {
            builder.AddContent(2, (MarkupString)"<span class='badge bg-danger me-1'>Important</span><span class='badge bg-warning text-dark'>Urgent</span>");
        }
        else if (Email.IsImportant && !Email.IsUrgent)
        {
            builder.AddContent(1, (MarkupString)"<span class='badge bg-danger'>Important</span>");
        }
        else if (!Email.IsImportant && Email.IsUrgent)
        {
            builder.AddContent(0, (MarkupString)"<span class='badge bg-warning text-dark'>Urgent</span>");
        }
    };

    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


        Email = await ApiService.GetByIdAsync<Services.EmailMessage>($"api/ListeMails/{Id}");
        Paragraphes = GetParagraphes();

    }

    private async Task SendReponse()
    {
        if (Email != 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("/listemails_card");
    }
    
    private async Task LoadEmailAsync(string uid)
    {
        Email = await ApiService.GetByIdAsync<Services.EmailMessage>($"api/ListeMails/{Id}");
        Paragraphes = GetParagraphes();
    }

    private async Task GenerateAgain()
    {
        var context = new List<ContextGeneration>();
        context.Add(new ContextGeneration { Name = "Type de mail", Description = "Mail reçu" });
        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", Email!.Reponse)
            .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;
            Email!.Reponse = nouvelleReponse!;

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


        }



    }
}

