using System.Net.Http.Json;
using System.Text.Json;
using Front.Program.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace Front.Program.Views.Project.ConnectUser;

public partial class Auth : ComponentBase, IDisposable
{
    [Inject] NavigationManager NavigationManager { get; set; } = default!;
    [Inject] LoadingService LoadingService { get; set; } = default!;
    [Inject] HttpClient Http { get; set; } = default!;
    [Inject] IJSRuntime JS { get; set; } = default!;

    protected override void OnInitialized()
    {
        // LocationChanged 이벤트 구독
        NavigationManager.LocationChanged += HandleLocationChanged;
    }

    private void HandleLocationChanged(object? sender, Microsoft.AspNetCore.Components.Routing.LocationChangedEventArgs e)
    {
        // 페이지 이동이 발생했을 때 로딩 상태 해제
        LoggerService.Write($"페이지 이동 감지: {NavigationManager.Uri}");
        LoadingService.HideLoading();
    }

    public void Dispose()
    {
        // 이벤트 구독 해제
        NavigationManager.LocationChanged -= HandleLocationChanged;
    }

    public async Task KakaoLogin(string? path = null)
    {
        try 
        {
            LoadingService.ShowLoading();

            var url = $"/api/v1/out/user/kakao/auth?redirectPath={Uri.EscapeDataString(path ?? "/about")}";
            var response = await Http.GetFromJsonAsync<JsonElement>(url);
            var kakaoUrl = response.GetProperty("url").GetString();

            if (!string.IsNullOrEmpty(kakaoUrl))
            {
                // JavaScript를 통해 페이지 이동
                await JS.InvokeVoidAsync("eval", $"window.location.replace('{kakaoUrl}')");
            }
        }
        catch (Exception ex)
        {
            LoggerService.Write($"카카오 로그인 오류: {ex.Message}");
            LoadingService.HideLoading();
        }
    }
}