@inject ReAct_PME.WebUI.ServicesUI.ApiService ApiService
@using Blazored.Modal;
@using Blazored.Modal.Services;
@inject Blazored.Modal.Services.IModalService Modal
@using System.Linq
@inject NavigationManager Navigation
@inject IToastService ToastService
@inject Blazored.LocalStorage.ILocalStorageService localStorage
@inject HttpClient Http
@using Blazored.Toast.Configuration;
@using Blazored.Toast.Services;
@using System.Text;

<div class="modal fade show d-block" tabindex="-1" role="dialog">
	<div class="modal-backdrop fade show"></div>
	<div class="modal-dialog" style="z-index: 1050">
		<div class="modal-content" style="width:880px">
			
			<div class="modal-header" style="height:80px !important">
				<h2 class="text-center my-4" style="font-weight:bold; color:black !important">Nouvelle génération d'une réponse</h2>
			</div>

			<div class="modal-body">
				<div class="form-group row">
					<label class="col-sm-3 col-form-label" style="color:black">Réponse initiale : </label>
					<div class="col-sm-9">
						<textarea id="TXT_OLD_REPONSE" @bind="ReponseOld" class="form-control" rows="5" readonly />
					</div>
				</div>

				<div class="form-group row">
					<label class="col-sm-3 col-form-label" style="color:black">Expliquez votre demande : </label>
					<div class="col-sm-9">
						<textarea id="TXT_RAISONS" @bind="RaisonNewGenerate" class="form-control" @oninput="AutoResizeMESSAGE" rows="3" />
					</div>
				</div>
				<div class="form-group row">
					<label class="col-sm-3 col-form-label" style="color:black">Nouvelle réponse  : </label>
					<div class="col-sm-9">
						<textarea id="TXT_NEW_REPONSE" @bind="ReponseNew" class="form-control" rows="5" />
					</div>
				</div>
			</div>

			<div class="modal-footer">
				<button type="button" class="btn btn-primary me-2" @onclick="GenerateAgain" >Re-générer la réponse</button>
				<button type="button" class="btn btn-primary me-2" @onclick="OnValiderAsync" disabled="@IsValidateDisabled">Valider</button>
				<button type="button" class="btn btn-secondary" @onclick="Cancel">Annuler</button>
			</div>
		</div>
	</div>
</div>



@code {
	[CascadingParameter] public ModalParameters? Parameters { get; set; }
	[CascadingParameter] BlazoredModalInstance ModalInstance { get; set; } = default!;

	[Parameter] public string? ReponseOld { get; set; }
	[Parameter] public List<ContextGeneration>? Context { get; set; }

	private bool IsValidateDisabled = true;
	private string RaisonNewGenerate = "";
	private string ReponseNew = "";

	[Inject] IJSRuntime? JS { get; set; }
	private async Task AutoResizeMESSAGE(ChangeEventArgs e)
	{
		await Task.Delay(1);
		if (JS != null)
		{
			await JS.InvokeVoidAsync("resizeTextarea", "TXT_RAISONS");
		}
	}
	protected override async Task OnAfterRenderAsync(bool firstRender)
	{
		// Ajuste la hauteur une première fois quand le textarea est initialisé
		//await JS.InvokeVoidAsync("resizeTextarea", "TXT_OLD_REPONSE");
		//await JS.InvokeVoidAsync("resizeTextarea", "TXT_NEW_REPONSE");
	}

	private async Task OnValiderAsync()
	{
		await ModalInstance.CloseAsync(ModalResult.Ok(ReponseNew));
	}

	//private async Task Close() => await ModalInstance.CloseAsync();
	private async Task Cancel() => await ModalInstance.CancelAsync();
	private async Task GenerateAgain()
	{
		if(RaisonNewGenerate.Length == 0)
		{
			ToastService.ShowWarning("Vous n'avez pas indiqué de raions... Merci de renseigner 'pourquoi' vous voulez re-générer le mail proposé.", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
			return;
		}
		ReponseNew = "";

		List<string> lst = new();
		lst.Add(CreateContext());
		lst.Add(CreateQuery());

		var rep = await ApiService.EnvoiRequete<string[]>($"api/ListeMails/generateagain", lst.ToArray());
		ReponseNew = rep;
		IsValidateDisabled = false;
	}

	private string CreateContext()
	{
		StringBuilder sb = new();
		if (Context != null && Context.Count > 0)
		{
			foreach (var c in Context)
			{
				sb.Append($"{c.Name} : {c.Description}");
			}
		}
		string context = sb.ToString();
		return context;
	}

	private string CreateQuery()
	{
		string query = $"Un mail a été généré, le voici\n--- début de la réponse générée\n{ReponseOld}\n--- fin de la réponse générée\nIl faut le refaire pour les raisons suivantes :\n{RaisonNewGenerate}";
		return query;
    }
}