@page "/dt_conversation_ligne_list"
@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;


<h3 class="text-center my-4">Liste DT_CONVERSATION_LIGNE: @itemsFilteredSorted.Count() / @(items == null ? 0 : items.Count()) élément@(itemsFilteredSorted.Count() > 1 ? "s" : "")</h3>

<div class="container-fluid">

    <div class="button-container">
        <button class="btn-action btn-secondary" @onclick="RefreshPage">
            <i class="bi bi-arrow-clockwise"></i> Rafraîchir les données
        </button>
        <button class="btn-action btn-secondary" @onclick="RAZFilters">
            <i class="bi bi-funnel"></i> Vider les filtres
        </button>
        <button class="btn-action btn-primary" @onclick="CreateItem">
            <i class="bi bi-plus-circle"></i> Créer une nouvelle donnée
        </button>
    </div>
    <p/>

@if (items != null)
{
    <div class="table-responsive">
        <table class="table table_standard table-striped table-bordered">
            <thead class="table-dark">
                <tr>
                    <th><input class="form-control form-control-sm" @bind="FilterDT_CONVERSATION_LIBELLE" placeholder="Filtrer..." /></th>
					<th><input class="form-control form-control-sm" @bind="FilterDATE" placeholder="Filtrer..." /></th>
                    <th><input class="form-control form-control-sm" @bind="FilterDomainRAG" placeholder="Filtrer..." /></th>
					<th><input class="form-control form-control-sm" @bind="FilterQUESTION" placeholder="Filtrer..." /></th>
					<th><input class="form-control form-control-sm" @bind="FilterMODELE" placeholder="Filtrer..." /></th>
					<th><input class="form-control form-control-sm" @bind="FilterSystemDateCreated" placeholder="Filtrer..." /></th>
					<th><select class="form-select form-select-sm" style="min-width: 80px;" @bind="FilterIsEnabled">
							<option value="">Tous</option>
							<option value="true">True</option>
							<option value="false">False</option>
						</select></th>


                    <th></th>
                </tr>
                <tr>
                    <th class="hover-cursor th_td_standard" @onclick="() => SortByColumn(DT_CONVERSATION_LIBELLE)">ID_CONVERSATION @GetSortIcon(DT_CONVERSATION_LIBELLE) </th>
                    <th class="hover-cursor th_td_standard" @onclick="() => SortByColumn(nameof(Domain.DT_CONVERSATION_LIGNE.DATE))">DATE  @GetSortIcon(nameof(Domain.DT_CONVERSATION_LIGNE.DATE))</th>
                    <th class="hover-cursor th_td_standard" @onclick="() => SortByColumn(nameof(Domain.DT_CONVERSATION_LIGNE.DomainRAG))">Domaine RAG @GetSortIcon(nameof(Domain.DT_CONVERSATION_LIGNE.DomainRAG))</th>
					<th class="hover-cursor th_td_standard" @onclick="() => SortByColumn(nameof(Domain.DT_CONVERSATION_LIGNE.QUESTION))">QUESTION  @GetSortIcon(nameof(Domain.DT_CONVERSATION_LIGNE.QUESTION))</th>
					<th class="hover-cursor th_td_standard" @onclick="() => SortByColumn(nameof(Domain.DT_CONVERSATION_LIGNE.MODELE))">MODELE  @GetSortIcon(nameof(Domain.DT_CONVERSATION_LIGNE.MODELE))</th>
					<th class="hover-cursor th_td_standard" @onclick="() => SortByColumn(nameof(Domain.DT_CONVERSATION_LIGNE.SystemDateCreated))">SystemDateCreated  @GetSortIcon(nameof(Domain.DT_CONVERSATION_LIGNE.SystemDateCreated))</th>
					<th class="hover-cursor th_td_standard" @onclick="() => SortByColumn(nameof(Domain.DT_CONVERSATION_LIGNE.IsEnabled))">IsEnabled  @GetSortIcon(nameof(Domain.DT_CONVERSATION_LIGNE.IsEnabled))</th>

                    <th class="th_td_standard">Actions</th>
                </tr>
            </thead>
            <tbody>
            @foreach (var item in itemsFilteredSorted)
            {
                <tr>
                    <td class="th_td_standard">@(item.DT_CONVERSATION is not null ? item.DT_CONVERSATION.LIBELLE : "")</td>
					<td class=" th_td_standard">@item.DATE.ToString("dd/MM/yyyy")</td>
                    <td class=" th_td_standard">@item.DomainRAG</td>                           
                    <td class=" th_td_standard">@item.QUESTION</td>
					<td class=" th_td_standard">@item.MODELE</td>
					<td class=" th_td_standard">@item.SystemDateCreated.ToString("dd/MM/yyyy")</td>
					<td class=" th_td_standard">@item.IsEnabled.ToString()</td>

                    
                    <td class="col-actions">
                        <div class="action-buttons">
                            <button class="btn-icon btn-edit" @onclick="() => EditItem(item.ID_CONVERSATION_LIGNE)" data-bs-toggle="tooltip" data-bs-placement="top" title="Modifier cet élément">
                                <i class="bi bi-pencil"></i>
                            </button>
                            <button class="btn-icon btn-delete" @onclick="() => DeleteItem(item.ID_CONVERSATION_LIGNE)" data-bs-toggle="tooltip" data-bs-placement="top" title="Supprimer cet élément">
                                <i class="bi bi-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            }
            </tbody>
        </table>
    </div>
}
else
{
    <div class="alert alert-info text-center p-2" role="alert">
        <i class="bi bi-info-circle"></i> En cours de chargement ou pas de données disponibles.
    </div>
}

    <!-- FAIRE APPARAITRE LES TOOLTIPS DES BOUTONS-->
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
        });
    </script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">

</div>

@code {

    #region Propriété JSRuntime
    [Inject]
    private IJSRuntime? JSRuntime { get; set; }
    #endregion

    #region Listes (native et FilteredSorted )
    private IEnumerable<Domain.DT_CONVERSATION_LIGNE_DTO>? items;
    /*
    * On ne filtre pas les Guid
    * Manipulations particulères pour les nullables
    */
    private IEnumerable<Domain.DT_CONVERSATION_LIGNE_DTO> itemsFilteredSorted =>
    items == null ? Enumerable.Empty<Domain.DT_CONVERSATION_LIGNE_DTO>() :
    items
    .Where(p =>

        (string.IsNullOrEmpty(FilterDATE) || p.DATE.ToString("dd-MM-yyyy").Contains(FilterDATE)) &&
        (string.IsNullOrEmpty(FilterDomainRAG) || p.DomainRAG != null &&  p.DomainRAG.ToString().Contains(FilterDomainRAG, StringComparison.OrdinalIgnoreCase)) &&
        (string.IsNullOrEmpty(FilterQUESTION) || p.QUESTION.ToString().Contains(FilterQUESTION, StringComparison.OrdinalIgnoreCase)) &&
        (string.IsNullOrEmpty(FilterREPONSE) || p.REPONSE.ToString().Contains(FilterREPONSE, StringComparison.OrdinalIgnoreCase)) &&
        (string.IsNullOrEmpty(FilterMODELE) || p.MODELE.ToString().Contains(FilterMODELE, StringComparison.OrdinalIgnoreCase)) &&
        (string.IsNullOrEmpty(FilterSystemDateCreated) || p.SystemDateCreated.ToString("dd-MM-yyyy").Contains(FilterSystemDateCreated)) &&
        (string.IsNullOrEmpty(FilterSystemDateUpdated) || p.SystemDateUpdated.ToString("dd-MM-yyyy").Contains(FilterSystemDateUpdated)) &&
        (string.IsNullOrEmpty(FilterIsEnabled) || p.IsEnabled.ToString().Contains(FilterIsEnabled, StringComparison.OrdinalIgnoreCase)) &&
        (string.IsNullOrEmpty(FilterDT_CONVERSATION_LIBELLE) || p.DT_CONVERSATION!.LIBELLE.Contains(FilterDT_CONVERSATION_LIBELLE, StringComparison.OrdinalIgnoreCase)) 
    )
    .OrderByDynamic(CurrentSortColumn!, IsAscending);

    #endregion

    #region Filtres

    private string FilterDATE = "";
    private string FilterDomainRAG = "";
    private string FilterQUESTION = "";
	private string FilterREPONSE = "";
	private string FilterMODELE = "";
	private string FilterSystemDateCreated = "";
	private string FilterSystemDateUpdated = "";
	private string FilterIsEnabled = "";
	private string FilterDT_CONVERSATION_LIBELLE = "";

    #endregion
    
    #region Variables FK pour le tri
	private string DT_CONVERSATION_LIBELLE = "DT_CONVERSATION.LIBELLE";

    #endregion

    #region Tri
    private string? CurrentSortColumn = null;
    private bool IsAscending = true;
    #endregion

    #region Méthodes
    protected override async Task OnInitializedAsync()
    {
        #region Vérification si utilisateur est connecté et s''il a les droits

        var tok = await PagesInitializer.VerifConnexionAndRules(AuthenticationStateProvider, Navigation, Http, ToastService, "api/DT_CONVERSATION_LIGNE_DTO");
        if (tok == null || tok.Length == 0)
            return;
        else
            AuthService.SetToken(tok);

        #endregion

		#region Charger les items
		// EXEMPLES DE CHARGEMENT SELON LE PROFIL : à customiser

		if ((AuthService == null || AuthService.ID == null || AuthService.ID == "") || (AuthService.IsAdmin == true))
		{
			// ici, on part du principe que la connexion n'est pas sécurisée par LOGIN / MOT DE PASSE ou alors ADMIN donc accès à tout pour tous
			items = await ApiService.GetAllAsync<IEnumerable<Domain.DT_CONVERSATION_LIGNE_DTO>>("api/DT_CONVERSATION_LIGNE_DTO/ADMIN");
		}
		else
		{
			// ici, on peut gérer le chargement de manière plus restictive, avec ces endpoints qui existent, ou en créer d'autres
			// et tester de manière dynamique le profil de l'utilisateur connecté avec : AuthService.IsAdmin ou AuthService.ISManager ou AuthService.IsOnlyUser 
			items = await ApiService.GetAllAsync<IEnumerable<Domain.DT_CONVERSATION_LIGNE_DTO>>("api/DT_CONVERSATION_LIGNE_DTO");

			//string id = AuthService.ID; // par exemple

			//items = await ApiService.GetAllAsync<IEnumerable<Domain.DT_CONVERSATION_LIGNE>>($"api/DT_CONVERSATION_LIGNE/ID_CONVERSATION/{id}");
		}
		#endregion


    }

    private void RefreshPage()
    {
        Navigation.NavigateTo($"/dt_conversation_ligne_list");  
    }

    private void EditItem(Guid id)
    {
        Navigation.NavigateTo($"/dt_conversation_ligne_edit/{id}");
    }

    private async Task DeleteItem(Guid id)
    {
        try
        {
            // Affichage du message d'avertissement à l'utilisateur
            bool confirmDelete = await ShowConfirmationDialog("Confirmer la suppression", "Voulez-vous vraiment supprimer cet élément ?");

            // Cas de la suppression annulée
            if (!confirmDelete)
            {
                ToastService.ShowWarning("Suppression annulée.", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
                return;
            }

            // Cas de la suppression confirmée
            bool b = await ApiService.DeleteAsync($"api/DT_CONVERSATION_LIGNE_DTO/{id}");
            if(b)
            {
                ToastService.ShowSuccess("Suppression réussie !", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
                await Task.Delay(1000);
                items = await ApiService.GetAllAsync<IEnumerable<Domain.DT_CONVERSATION_LIGNE_DTO>>("api/DT_CONVERSATION_LIGNE_DTO");                                                                 
            }
            else
            {
                ToastService.ShowError($"Erreur : Suppression impossible.", 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 CreateItem()
    {
        Navigation.NavigateTo("/dt_conversation_ligne_create");
    }

    private void SortByColumn(string columnName)
    {
        if (CurrentSortColumn == columnName)
        {
            IsAscending = !IsAscending; // Inverse le tri si déjà trié par cette colonne
        }
        else
        {
            CurrentSortColumn = columnName;
            IsAscending = true; // Tri par défaut en ordre ascendant
        }
    }

    private string GetSortIcon(string columnName)
    {
        bool b = false;
        if (CurrentSortColumn != null)
        {
            var tab = CurrentSortColumn.Split('.');
            b = (tab.Length == 2 && columnName.Contains(tab[0]) && columnName.Contains(tab[1]));
        }

        if (CurrentSortColumn == columnName)
        {
            return IsAscending ? " ▲" : " ▼"; // Flèche selon l'ordre
        }
        return string.Empty; // Pas d'icône si la colonne n'est pas triée
    }

    private void RAZFilters()
    {
		
		FilterDATE = "";
		FilterQUESTION = "";
		FilterREPONSE = "";
		FilterMODELE = "";
		FilterSystemDateCreated = "";
		FilterSystemDateUpdated = "";
		FilterIsEnabled = "";
		FilterDT_CONVERSATION_LIBELLE = "";

    }

    private async Task<bool> ShowConfirmationDialog(string title, string message)
    {
        // Utilisation de la boîte de dialogue native confirm() via JavaScript
        if (JSRuntime != null)
            return await JSRuntime.InvokeAsync<bool>("confirm", $"{title}\n\n{message}");
        else
            return false;
    }
    #endregion
}


