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

using Front.Program.ViewModels;
using Front.Program.Services;

namespace Front.Program.Views.Project;

public partial class About : ComponentBase, IDisposable
{
    [Inject]
    NavigationManager Navigation { get; set; } = default!;
    
    [Inject]
    StorageService StorageService { get; set; } = default!;
    
    [Inject] 
    QueryParamService QueryParamService { get; set; } = default!;
    
    [Inject] UserStateService UserStateService { get; set; } = default!;

    private bool _isProcessing = false;
    
    protected override void OnInitialized()
    {
        Navigation.LocationChanged += HandleLocationChanged;
        HandleLocationChanged(this, new LocationChangedEventArgs(Navigation.Uri, false));
    }

    public void Dispose()
    {
        Navigation.LocationChanged -= HandleLocationChanged;
    }
    
    private async void HandleLocationChanged(object? sender, LocationChangedEventArgs e)
    {
        try
        {
            // 다중 실행 방지
            if (_isProcessing) return;
            _isProcessing = true;
            
            var uri = Navigation.ToAbsoluteUri(Navigation.Uri);
            LoggerService.Write($"리다이렉트된 URI: {uri}");

            // 쿼리 파라미터가 있는 경우에만 처리
            if (!string.IsNullOrEmpty(uri.Query))
            {
                var queryParam = QueryParamService.ParseQueryParam(uri);
                await QueryParamService.AuthCheck(queryParam, StorageService);
                
                // 유저 정보 확인하는거 (로그인 했으니 값 가져와야지)
                await UserStateService.GetUserDataAsync();
                
                // 쿼리 파라미터를 제거한 기본 URI로 리다이렉트
                var baseUri = uri.GetLeftPart(UriPartial.Path);
                LoggerService.Write($"리다이렉트할 URI: {baseUri}");
                await InvokeAsync(StateHasChanged); // StateHasChanged를 호출하여 UI 업데이트
                Navigation.NavigateTo(baseUri, forceLoad: false);
            }
        }
        catch (Exception ex)
        {
            LoggerService.Write($"Error in HandleLocationChanged: {ex.Message}");
        }
        finally
        {
            _isProcessing = false;
        }
    }
}