
@using DiunaBI.UI.Shared.Services
@using Microsoft.Extensions.Configuration
@inject IJSRuntime JS
@inject IConfiguration Configuration
@inject AuthService AuthService
@inject NavigationManager NavigationManager
@inject IGoogleAuthService? GoogleAuthService

<MudCard Class="login-card" Elevation="8">
    <MudCardContent Class="pa-8 d-flex flex-column align-center">
        <MudText Typo="Typo.h4" Class="mb-4">Welcome to DiunaBI</MudText>
        <MudText Typo="Typo.body1" Class="mb-6 text-center">
            Sign in using your Google account
        </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>
                <span>Verifying...</span>
            }
            else
            {
                <span>Sign in with Google</span>
            }
        </MudButton>
        
        @if (!string.IsNullOrEmpty(_errorMessage))
        {
            <MudAlert Severity="Severity.Error" Class="mt-4" Dense="true">
                @_errorMessage
            </MudAlert>
        }

        @if (_sessionExpired)
        {
            <MudAlert Severity="Severity.Warning" Class="mt-4" Dense="true">
                Your session has expired. Please sign in again.
            </MudAlert>
        }
    </MudCardContent>
</MudCard>

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

    protected override void OnInitialized()
    {
        // Check if sessionExpired query parameter is present
        var uri = new Uri(NavigationManager.Uri);
        var query = System.Web.HttpUtility.ParseQueryString(uri.Query);
        _sessionExpired = query["sessionExpired"] == "true";

        if (_sessionExpired)
        {
            Console.WriteLine("⚠️ Session expired - user redirected to login");
        }
    }

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

            // Initialize JavaScript Google SDK for web (both null service and WebGoogleAuthService)
            // Skip only for mobile platform-specific auth (MobileGoogleAuthService)
            var isMobileAuth = GoogleAuthService != null && GoogleAuthService.GetType().Name == "MobileGoogleAuthService";

            if (!isMobileAuth)
            {
                await InitializeGoogleSignIn();
            }
            else
            {
                Console.WriteLine("📱 Using platform-specific Google auth service");
                _isInitialized = true;
            }
        }
    }

    private async Task InitializeGoogleSignIn()
    {
        try
        {
            if (_isInitialized) return;

            var clientId = Configuration["GoogleAuth:ClientId"];
            Console.WriteLine($"🔍 Reading GoogleAuth:ClientId from configuration: '{clientId}'");

            if (string.IsNullOrEmpty(clientId))
            {
                _errorMessage = "Google ClientId is not configured in appsettings.";
                Console.Error.WriteLine("❌ Google ClientId is NULL or EMPTY in configuration!");
                return;
            }

            Console.WriteLine($"✅ Calling initGoogleSignIn with clientId: {clientId}");
            await JS.InvokeVoidAsync("initGoogleSignIn", clientId);
            _isInitialized = true;
        }
        catch (Exception ex)
        {
            _errorMessage = "Google Sign-In initialization error.";
            Console.Error.WriteLine($"❌ Google Sign-In initialization error: {ex.Message}");
            Console.Error.WriteLine($"Stack trace: {ex.StackTrace}");
        }
    }

    private async Task HandleGoogleSignIn()
    {
        try
        {
            _isLoading = true;
            _errorMessage = string.Empty;
            StateHasChanged();

            // Use platform-specific auth if available (mobile), otherwise use JavaScript (web)
            if (GoogleAuthService != null)
            {
                Console.WriteLine("📱 Using mobile Google auth");
                var success = await GoogleAuthService.SignInAsync();

                if (success)
                {
                    Console.WriteLine("✅ Mobile auth successful, navigating...");
                    NavigationManager.NavigateTo("/dashboard", replace: true);
                }
                else
                {
                    _errorMessage = "Login failed. Please try again";
                    _isLoading = false;
                    StateHasChanged();
                }
            }
            else
            {
                Console.WriteLine("🌐 Using web JavaScript Google auth");
                await JS.InvokeVoidAsync("requestGoogleSignIn");
            }
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"❌ HandleGoogleSignIn error: {ex.Message}");
            _errorMessage = "Login error. Please try again";
            _isLoading = false;
            StateHasChanged();
        }
    }

    [JSInvokable]
    public static async Task OnGoogleSignInSuccess(string googleCredential, string fullName, string email, string avatarUrl)
    {
        Console.WriteLine($"=== OnGoogleSignInSuccess: {email} ===");
        
        if (_instance != null)
        {
            try
            {
                // Waliduj użytkownika w backendzie DiunaBI
                var (success, errorMessage) = await _instance.AuthService.ValidateWithBackendAsync(
                    googleCredential, fullName, email, avatarUrl);
                
                if (success)
                {
                    Console.WriteLine("✅ User validated, navigating to dashboard");
                    _instance._isLoading = false;
                    _instance._errorMessage = string.Empty;
                    _instance.NavigationManager.NavigateTo("/dashboard", replace: true);
                }
                else
                {
                    Console.WriteLine($"❌ Validation failed: {errorMessage}");
                    _instance._isLoading = false;
                    _instance._errorMessage = errorMessage ?? "Login failed.";
                }

                await _instance.InvokeAsync(() => _instance.StateHasChanged());
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"❌ OnGoogleSignInSuccess error: {ex.Message}");
                _instance._isLoading = false;
                _instance._errorMessage = "User verification error.";
                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 = "Google login error. Please try again";
            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>