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

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

namespace Front.Program.Layout;

public partial class MainLayout : LayoutComponentBase, IDisposable
{
    [Inject] NavigationManager Navigation { get; set; } = default!;
    [Inject] LoadingService LoadingService { get; set; } = default!;
    [Inject] UserStateService UserStateService { get; set; } = default!;
    
    
    private bool _isLoading = false;

    // 경로의 시작 부분
    // protected bool isHidePrjTop => Navigation.ToBaseRelativePath(Navigation.Uri).StartsWith("auth", StringComparison.OrdinalIgnoreCase);
    protected bool isIntro => Navigation.ToBaseRelativePath(Navigation.Uri).StartsWith("am/intro", StringComparison.OrdinalIgnoreCase)
                              || Navigation.ToBaseRelativePath(Navigation.Uri).StartsWith("/", StringComparison.OrdinalIgnoreCase);
    
    // 경로의 끝 부분
    protected bool isHidePrjTop => Navigation.ToBaseRelativePath(Navigation.Uri).EndsWith("auth", StringComparison.OrdinalIgnoreCase);
    protected bool isAcademy => Navigation.ToBaseRelativePath(Navigation.Uri).StartsWith("am", StringComparison.OrdinalIgnoreCase);
    
    // 경로 일치
    // protected bool isIntro => Navigation.ToBaseRelativePath(Navigation.Uri).Equals("am/intro", StringComparison.OrdinalIgnoreCase);
    
    protected override async Task OnInitializedAsync()
    {
        LoggerService.Write("MainLayout OnInitializedAsync 시작");
        LoadingService.OnChange += StateHasChanged;
        Navigation.LocationChanged += HandleLocationChanged;
        HandleLocationChanged(this, new LocationChangedEventArgs(Navigation.Uri, false));

        LoggerService.Write("MainLayout: UserStateService.GetUserDataAsync 호출 전");
        await UserStateService.GetUserDataAsync();
        LoggerService.Write($"MainLayout: UserStateService.isLogin 상태: {UserStateService.isLogin}");

        // 학원 정보 로드 및 실패 시 처리
        var academyResult = await UserStateService.GetAcademy();
        LoadingService.ShowLoading();
        if (academyResult.success)
        {
            if (academyResult.simpleAcademy != null && academyResult.simpleAcademy.Any())
            {
                UserStateService.academyItems = academyResult.simpleAcademy.ToArray();
                LoggerService.Write($"MainLayout: academyItems 로드 성공. {UserStateService.academyItems.Length}개");
            }
            else
            {
                LoggerService.Write("MainLayout: 로드된 학원 정보가 없습니다.");
            }
        }
        else
        {
            LoggerService.Write("MainLayout: 서버 세션에서 학원 정보 불러오기 실패. 사용자 상태 초기화.");
            await UserStateService.ClearUserStateAsnyc();
        }

        if (isAcademy)
        {
            if(!UserStateService.isLogin || UserStateService.UserData == null)
            {
                LoggerService.Write("로그인 상태가 아닙니다. 초기로 돌립니다.");
                if (isIntro) { } 
                else
                {
                    await UserStateService.ClearUserStateAsnyc();
                    LoadingService.HideLoading();
                    Navigation.NavigateTo("/");
                }
            }
            LoadingService.HideLoading();
        }
    }

    // 페이지의 URL이 변경될 때마다 실행되는 이벤트 핸들러
    private async void HandleLocationChanged(object? sender, LocationChangedEventArgs e)
    {
        LoadingService.HideNavigationLoading();
    }

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