using Front.Program.Models;
using Front.Program.Services;
using Front.Program.ViewModels;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Routing;

namespace Front.Program.Views.Academy;

public partial class AcademyIntro : 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!;
    [Inject] LoadingService LoadingService { get; set; } = default!;
    
    private bool _isProcessing = false;
    
    protected override async void OnInitialized()
    {
        try
        {
            Navigation.LocationChanged += HandleLocationChanged;
            HandleLocationChanged(this, new LocationChangedEventArgs(Navigation.Uri, false));
            if (!UserStateService.isFirstCheck)
            {
                LoadingService.ShowLoading();
                await UserStateService.GetUserDataAsync();
                var aca = await UserStateService.GetAcademy();

                if (aca.success)
                {
                    if (aca.simpleAcademy.Count > 0)
                    {
                        UserStateService.academyItems = aca.simpleAcademy.ToArray();
                        LoggerService.Write($"academyItems: {UserStateService.academyItems.Length}개");
                    }
                    LoggerService.Write("아카데미 정보가 없습니다. 로그인 상태를 확인해주세요.");
                }
                else
                {
                    LoggerService.Write("서버 세션에서 불러오기 실패");
                    await UserStateService.ClearUserStateAsnyc();
                    
                }
                LoggerService.Write($"academy: {string.Join(", ", UserStateService.academyItems.Select(a => a.name))}");
                
            }
        }
        finally
        {
            LoadingService.HideLoading();
            await InvokeAsync(StateHasChanged);
        }
        // 유저 값 가져오면서 같이 academy 정보도 가져와야지
    }

    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))
            {
                LoadingService.ShowLoading();
                var queryParam = QueryParamService.ParseQueryParam(uri);
                await QueryParamService.AuthCheck(queryParam, StorageService);
                
                // 유저 정보 확인하는거 (로그인 했으니 값 가져와야지)
                await UserStateService.GetUserDataAsync();
                var aca = await UserStateService.GetAcademy();
                
                if (aca.success)
                {
                    if (aca.simpleAcademy.Count > 0)
                    {
                        UserStateService.academyItems = aca.simpleAcademy.ToArray(); 
                        
                        LoggerService.Write($"academyItems: {UserStateService.academyItems.Length}개");
                    }
                    LoggerService.Write("아카데미 정보가 없습니다. 로그인 상태를 확인해주세요.");
                }
                LoggerService.Write($"academy: {string.Join(", ", UserStateService.academyItems.Select(a => a.name))}");
                
                // // 쿼리 파라미터를 제거한 기본 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
        {
            LoadingService.HideLoading();
            _isProcessing = false;
            
        }
    }
    
    protected void OnClickLogin()
    {
        Navigation.NavigateTo("/am/auth");
    }
}