using Blazored.Modal;
using Blazored.Modal.Services;
using Blazored.Toast.Configuration;
using Blazored.Toast.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using ReAct_PME.WebUI.ServicesUI;

namespace ReAct_PME.WebUI.Pages
{
    public partial class Home : ComponentBase
    {
        [Inject] private NavigationManager Navigation { get; set; } = default!;
        [Inject] private AuthService AuthService { get; set; } = default!;
        [Inject] private ApiService ApiService { get; set; } = default!;
        [Inject] private Blazored.LocalStorage.ILocalStorageService localStorage { get; set; } = default!;
        [Inject] private HttpClient Http { get; set; } = default!;
        [Inject] private AuthenticationStateProvider AuthenticationStateProvider { get; set; } = default!;
        [Inject] private IToastService ToastService { get; set; } = default!;
        [CascadingParameter] public IModalService Modal { get; set; } = default!;

        //private string MessagePerso = "";
        private List<string>? LstMessagePerso = new();
        private List<Paragraphe> Paragraphes = new();

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

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

        protected override void OnInitialized()
        {
            #region Vérification si utilisateur est connecté (uniquement)

            var bOk = PagesInitializer.VerifConnexion(AuthService, AuthenticationStateProvider, Navigation);
            if (!bOk)
            {
                Navigation.NavigateTo("/login");
                return;
            }
            #endregion
        }

        protected override async Task OnInitializedAsync()
        {
            #region Vérification si utilisateur est connecté et s'il a les droits
        
            var ID_USER = AuthService.ID;
            var IsManager = (AuthService.IsManager == true);
            var tok = await PagesInitializer.VerifConnexionAndRules(AuthenticationStateProvider, Navigation, Http, ToastService, $"api/Auth/info/test/{ID_USER}/{IsManager}");
            if (tok == null || tok.Length == 0)
            {
                Navigation.NavigateTo("/login");
                return;
            }
            else
               AuthService.SetToken(tok);
        
          #endregion

            #region Affichage infos perso
        
            try
            {
                LstMessagePerso = await GetAllInfo();
                Paragraphes = GetParagraphes(LstMessagePerso);
                //ToastService.ShowSuccess("Let's Go !", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
        
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"Erreur HTTP: {ex.Message}");
                ToastService.ShowError($"Erreur inattendue : {ex.Message}", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
        
            }
            catch(Exception ex)
            {
                Console.WriteLine($"Erreur inattendue: {ex.Message}");
                ToastService.ShowError($"Erreur inattendue : {ex.Message}", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
        
            }
            #endregion
        }

        private List<Paragraphe> GetParagraphes(List<string>? lstMessagePerso)
        {
            List<Paragraphe> lstParagrah = new();
            if (lstMessagePerso != null && lstMessagePerso.Count > 0)
            {
                Paragraphe oneParagraph = new();
                int i = 0;
                List<string> allText = new();
                foreach (var s1 in lstMessagePerso)
                {
                    string s = s1.Replace("<br/>", "").Replace("<li>", "").Replace("</li>", "").Replace("<ul>", "").Replace("</ul>", "").Replace("<strong>", "").Replace("</strong>", "").Trim();
                    if(s != "")
                    {
                        if (s.StartsWith(">>>"))
                        {
                            allText.Add(s.Replace(">>> ",""));
                        }
                        else
                        {
                            if (i > 0)
                            {
                                oneParagraph.Text = allText;
                                lstParagrah.Add(oneParagraph);
                                allText = new();
                            }
                            if (s != "")
                            {
                                oneParagraph = new();
                                oneParagraph.Id = i;
                                oneParagraph.Title = s;
                                if (s.Contains("En tant qu") || s.Contains("VOS INFORMATIONS PERSONNELLES"))
                                    oneParagraph.IsBold = true;
                            }

                            i++;
                        }
                    }
                }
                oneParagraph.Text = allText;
                lstParagrah.Add(oneParagraph);
            }
            return lstParagrah;
        }

        private async Task<List<string>?> GetAllInfo()
        {
            await Task.Delay(1);
            if (AuthService.ID == "")
                return null;

            string ID_WORK_SORCE = AuthService.ID!;
            string IsManager = AuthService.IsManager == true ? "true":"false";
            var sReturn = await ApiService.GetAllInfoById<List<string>>($"api/Auth/info/{ID_WORK_SORCE}/{IsManager}");


            return sReturn!;
        }
        /*
        public async Task LogoutAsync()
        {
            var authProvider = (CustomAuthenticationStateProvider)AuthenticationStateProvider;
            authProvider.NotifyUserLogout();
            await localStorage.RemoveItemAsync("authToken");
            AuthService.Deconnect();
            Navigation.NavigateTo("/login", forceLoad: true);
        }
        */
        private async Task ShowModal()
        {
            //https://github.com/Blazored/Modal/tree/main/samples/InteractiveWebAssembly/Pages

            var options = new ModalOptions
                {
                    //Class = "modal-custom-large", // ou "modal-xl" selon le besoin
                    //DisableBackgroundCancel = true,
                    //Position = ModalPosition.Middle,
                    UseCustomLayout = true
                };

            var parameters = new ModalParameters()
                .Add("DisplayMessage", "Message transmis");
            var modal = Modal.Show<ExempleModal>(("EXEMPLE DE MODALE").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)
            {
                ToastService.ShowWarning("La modale a été confirmée.", settings => { settings.Timeout = 2000; settings.IconType = IconType.None; settings.Position = ToastPosition.BottomCenter; });
            }
        }
    }
}
