using System.Net.Http.Json;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using WF_WebAdmin.Service;
using System.Globalization;

namespace WF_WebAdmin.Pages
{
    public partial class AjoutCitationComplex
    {
        [Inject] private HttpClient Http { get; set; } = default!;
        [Inject] private IJSRuntime JS { get; set; } = default!;

        private Dictionary<string, int> commentairesParMois = new();
        private bool _isRendered = false;
        private static readonly string[] MoisNoms = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[..12];
        private int selectedYear = DateTime.Now.Year;

        protected override async Task OnInitializedAsync()
        {
            await ChargerCommentaires();
        }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender && _isRendered == false)
            {
                _isRendered = true;
                await JS.InvokeVoidAsync("updateChart", commentairesParMois, selectedYear);
            }
        }

        private async Task ChargerCommentaires()
        {
            try
            {
                var commentaires = await Http.GetFromJsonAsync<List<Commentaire>>("fake-dataCommentaty.json");
                if (commentaires != null)
                {
                    commentairesParMois = MoisNoms.ToDictionary(m => m, _ => 0);

                    foreach (var commentaire in commentaires)
                    {
                        if (!string.IsNullOrEmpty(commentaire.DateC) && DateTime.TryParseExact(commentaire.DateC, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date))
                        {
                            if (date.Year == selectedYear)
                            {
                                var moisNom = MoisNoms[date.Month - 1];
                                if (commentairesParMois.ContainsKey(moisNom))
                                {
                                    commentairesParMois[moisNom]++;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erreur de chargement des commentaires: " + ex.Message);
            }
        }

        private async Task ChangerAnnee(int delta)
        {
            selectedYear += delta;
            await ChargerCommentaires();
            await JS.InvokeVoidAsync("updateChart", commentairesParMois, selectedYear);
        }

        private class Commentaire
        {
            public int IdComment { get; set; }
            public int Quote { get; set; }
            public int Users { get; set; }
            public string DateC { get; set; } = "";
            public string Comment { get; set; } = "";
        }
    }
}
