using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Routing;

using Front.Program.Views.Project;
using Front.Program.Services;

namespace Front.Program.Layout;

public partial class MainLayout : LayoutComponentBase, IDisposable
{
    [Inject]
    NavigationManager Navigation { get; set; } = default!;

    [Inject]
    LoadingService LoadingService { get; set; } = default!;

    [Inject]
    StorageService StorageService { get; set; } = default!;

    // 경로의 시작 부분
    // protected bool isHidePrjTop => Navigation.ToBaseRelativePath(Navigation.Uri).StartsWith("auth", StringComparison.OrdinalIgnoreCase);

    // 경로의 끝 부분
    protected bool isHidePrjTop => Navigation.ToBaseRelativePath(Navigation.Uri).EndsWith("auth", StringComparison.OrdinalIgnoreCase);

    protected override void OnInitialized()
    {
        LoadingService.OnChange += StateHasChanged;
        Navigation.LocationChanged += HandleLocationChanged;
        HandleLocationChanged(this, new LocationChangedEventArgs(Navigation.Uri, false));
    }

    private async void HandleLocationChanged(object? sender, LocationChangedEventArgs e)
    {
        LoadingService.HideNavigationLoading();
        
        var uri = Navigation.ToAbsoluteUri(Navigation.Uri);
        Console.WriteLine($"리다이렉트된 URI: {uri}");
        
        if (uri.Query.Contains("auth="))
        {
            var query = uri.Query.TrimStart('?');
            var parameters = query.Split('&')
                .Select(p => p.Split('='))
                .Where(p => p.Length == 2)
                .ToDictionary(p => p[0], p => p[1]);

            if (parameters.TryGetValue("auth", out var auth))
            {
                Console.WriteLine($"auth 파라미터 값: {auth}");
                if (auth == "true")
                {
                    await StorageService.SetItemAsync("IsLogin", "true");
                    Console.WriteLine("로그인 상태를 true로 설정했습니다.");
                }
                else
                {
                    await StorageService.RemoveItemAsync("IsLogin");
                    Console.WriteLine("로그인 상태를 제거했습니다.");
                }
                
                // 파라미터를 제거하고 리다이렉트
                var baseUri = uri.GetLeftPart(UriPartial.Path);
                Navigation.NavigateTo(baseUri, forceLoad: false);
            }
        }
    }

    public void Dispose()
    {
        LoadingService.OnChange -= StateHasChanged;
        Navigation.LocationChanged -= HandleLocationChanged;
    }
}