@using System.Globalization
@using SteUp.Shared.Components.SingleElements
@using SteUp.Shared.Core.Interface.IntegryApi
@using SteUp.Shared.Core.Interface.System.Network
@inherits LayoutComponentBase
@inject INetworkService NetworkService
@inject IIntegryApiService IntegryApiService

<MudThemeProvider Theme="_currentTheme" @ref="@_mudThemeProvider" @bind-IsDarkMode="@IsDarkMode" />
<MudPopoverProvider/>
<MudDialogProvider/>
<MudSnackbarProvider/>

<ConnectionState IsNetworkAvailable="IsNetworkAvailable" ServicesIsDown="ServicesIsDown" ShowWarning="ShowWarning" />

<div class="page">
    <NavMenu/>

    <main>
        <article>
            @Body
        </article>
    </main>
</div>

@code {
    private MudThemeProvider _mudThemeProvider = null!;
    private bool IsDarkMode { get; set; }
    private string _mainContentClass = "";

    //Connection state
    private bool _isNetworkAvailable;
    private bool _servicesIsDown;
    private bool _showWarning;

    private DateTime _lastApiCheck = DateTime.MinValue;
    private const int DelaySeconds = 90;

    private CancellationTokenSource? _cts;

    private bool ServicesIsDown
    {
        get => _servicesIsDown;
        set
        {
            if (_servicesIsDown == value) return;
            _servicesIsDown = value;
            StateHasChanged();
        }
    }

    private bool IsNetworkAvailable
    {
        get => _isNetworkAvailable;
        set
        {
            if (_isNetworkAvailable == value) return;
            _isNetworkAvailable = value;
            StateHasChanged();
        }
    }

    private bool ShowWarning
    {
        get => _showWarning;
        set
        {
            if (_showWarning == value) return;
            _showWarning = value;
            StateHasChanged();
        }
    }

    private readonly MudTheme _currentTheme = new()
    {
        PaletteLight = new PaletteLight()
        {
            Primary = "#ec4c41",
            Secondary = "#002339",
            Tertiary = "#dff2ff",
            TextPrimary = "#000"
        },
        PaletteDark = new PaletteDark
        {
            Primary = "#ec4c41",
            Secondary = "#002339",
            Tertiary = "#dff2ff",
            Surface = "#000406",
            Background = "#000406",
            TextPrimary = "#fff",
            GrayDark = "#E0E0E0"
        }
    };

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        // if (firstRender)
        // {
        //     var isDarkMode = LocalStorage.GetString("isDarkMode");

        //     if (isDarkMode == null && _mudThemeProvider != null)
        //     {
        //         IsDarkMode = await _mudThemeProvider.GetSystemPreference();
        //         await _mudThemeProvider.WatchSystemPreference(OnSystemPreferenceChanged);
        //         LocalStorage.SetString("isDarkMode", IsDarkMode.ToString());
        //         StateHasChanged();
        //     }
        //     else
        //     {
        //         IsDarkMode = bool.Parse(isDarkMode!);
        //     }

        //     if (IsDarkMode)
        //     {
        //         _mainContentClass += "is-dark";
        //         StateHasChanged();
        //     }
        // }
    }

    private async Task OnSystemPreferenceChanged(bool newValue)
    {
        IsDarkMode = newValue;
    }

    protected override void OnInitialized()
    {
        _cts = new CancellationTokenSource();
        _ = CheckConnectionState(_cts.Token);

        var culture = new CultureInfo("it-IT", false);

        CultureInfo.CurrentCulture = culture;
        CultureInfo.CurrentUICulture = culture;
    }

    private Task CheckConnectionState(CancellationToken token)
    {
        return Task.Run(async () =>
        {
            while (!token.IsCancellationRequested)
            {
                var isNetworkAvailable = NetworkService.IsNetworkAvailable();
                var servicesDown = ServicesIsDown;

                if (isNetworkAvailable && (DateTime.UtcNow - _lastApiCheck).TotalSeconds >= DelaySeconds)
                {
                    servicesDown = !await IntegryApiService.SystemOk();
                    _lastApiCheck = DateTime.UtcNow;
                }

                await InvokeAsync(async () =>
                {
                    IsNetworkAvailable = isNetworkAvailable;
                    ServicesIsDown = servicesDown;

                    await Task.Delay(1500, token);
                    ShowWarning = !(IsNetworkAvailable && !ServicesIsDown);
                    NetworkService.ConnectionAvailable = !ShowWarning;
                });

                await Task.Delay(500, token);
            }
        }, token);
    }

    public void Dispose()
    {
        _cts?.Cancel();
        _cts?.Dispose();
    }

}