
@using Microsoft.Extensions.Configuration
@using Bimix.UI.Shared.Services
@inject IJSRuntime JS
@inject IConfiguration Configuration
@inject AuthService AuthService
@inject NavigationManager NavigationManager

<MudCard Class="login-card" Elevation="8">
    <MudCardContent Class="pa-8 d-flex flex-column align-center">
        <MudText Typo="Typo.h4" Class="mb-4">Witaj w Bimix</MudText>
        <MudText Typo="Typo.body1" Class="mb-6 text-center">
            Zaloguj się używając konta Google
        </MudText>
        
        <MudButton
            Variant="Variant.Filled"
            StartIcon="@Icons.Custom.Brands.Google"
            Size="Size.Large"
            OnClick="HandleGoogleSignIn"
            Disabled="@_isLoading">
            @if (_isLoading)
            {
                <MudProgressCircular Class="mr-3" Size="Size.Small" Indeterminate="true"></MudProgressCircular>
            }
            else
            {
                <span>Zaloguj z Google</span>
            }
        </MudButton>
        
        @if (!string.IsNullOrEmpty(_errorMessage))
        {
            <MudAlert Severity="Severity.Error" Class="mt-4">
                @_errorMessage
            </MudAlert>
        }
    </MudCardContent>
</MudCard>

@code {
    private bool _isLoading = false;
    private string _errorMessage = string.Empty;
    private static LoginCard? _instance;
    private bool _isInitialized = false;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            _instance = this;
            await InitializeGoogleSignIn();
        }
    }

    private async Task InitializeGoogleSignIn()
    {
        try
        {
            if (_isInitialized) return;
            
            var clientId = Configuration["GoogleAuth:ClientId"];
            if (string.IsNullOrEmpty(clientId))
            {
                throw new Exception("Google ClientId is not configured.");
            }

            await JS.InvokeVoidAsync("initGoogleSignIn", clientId);
            _isInitialized = true;
        }
        catch (Exception ex)
        {
            _errorMessage = "Błąd inicjalizacji Google Sign-In.";
            Console.Error.WriteLine($"Google Sign-In initialization error: {ex.Message}");
        }
    }

    private async Task HandleGoogleSignIn()
    {
        try
        {
            _isLoading = true;
            _errorMessage = string.Empty;
            StateHasChanged();
            
            await JS.InvokeVoidAsync("requestGoogleSignIn");
        }
        catch (Exception ex)
        {
            _errorMessage = "Błąd podczas logowania. Spróbuj ponownie";
            _isLoading = false;
            StateHasChanged();
        }
    }

    [JSInvokable]
    public static async Task OnGoogleSignInSuccess(string accessToken, string fullName, string email, string avatarUrl)
    {
        Console.WriteLine($"Google Sign-In Success: {email}");
        
        if (_instance != null)
        {
            var userInfo = new UserInfo
            {
                FullName = fullName,
                Email = email,
                AvatarUrl = avatarUrl
            };
            
            await _instance.AuthService.SetAuthenticationAsync(accessToken, userInfo);
            
            _instance._isLoading = false;
            _instance._errorMessage = string.Empty;
            
            _instance.NavigationManager.NavigateTo("/dashboard", replace: true);
            
            await _instance.InvokeAsync(() => _instance.StateHasChanged());
        }
    }

    [JSInvokable]
    public static async Task OnGoogleSignInError(string error)
    {
        Console.WriteLine($"Google SignIn Error: {error}");

        if (_instance != null)
        {
            _instance._isLoading = false;
            _instance._errorMessage = "Błąd logowania Google. Spróbuj ponownie";
            await _instance.InvokeAsync(() => _instance.StateHasChanged());
        }
    }
}

<style>
    .login-card {
        max-width: 400px;
        width: 100%;
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
    }
</style>