using Microsoft.JSInterop;

namespace Bimix.UI.Shared.Services;

public class AuthService
{
    private readonly IJSRuntime _jsRuntime;
    private bool? _isAuthenticated; 
    
    public event Action<bool>? AuthenticationStateChanged;
    
    public AuthService(IJSRuntime jsRuntime)
    {
        _jsRuntime = jsRuntime;
    }
    
    public bool IsAuthenticated => _isAuthenticated ?? false;
    
    public async Task<bool> CheckAuthenticationAsync()
    {
        try
        {
            var token = await _jsRuntime.InvokeAsync<string?>("localStorage.getItem", "google_token");
            _isAuthenticated = !string.IsNullOrEmpty(token);
            
            Console.WriteLine($"AuthService.CheckAuthentication: token={(!string.IsNullOrEmpty(token) ? "EXISTS" : "NULL")}, isAuth={_isAuthenticated}");
            
            return _isAuthenticated.Value;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"AuthService.CheckAuthentication ERROR: {ex.Message}");
            _isAuthenticated = false;
            return false;
        }
    }
    
    public async Task SetAuthenticationAsync(string token)
    {
        try
        {
            await _jsRuntime.InvokeVoidAsync("localStorage.setItem", "google_token", token);
            _isAuthenticated = true;
            Console.WriteLine($"AuthService.SetAuthentication: token saved, isAuth={_isAuthenticated}");
            AuthenticationStateChanged?.Invoke(true);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"AuthService.SetAuthentication ERROR: {ex.Message}");
        }
    }
    
    public async Task ClearAuthenticationAsync()
    {
        try
        {
            await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", "google_token");
            _isAuthenticated = false;
            Console.WriteLine($"AuthService.ClearAuthentication: token removed");
            AuthenticationStateChanged?.Invoke(false);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"AuthService.ClearAuthentication ERROR: {ex.Message}");
        }
    }
    
    public async Task<string?> GetTokenAsync()
    {
        if (_isAuthenticated != true) 
        {
            await CheckAuthenticationAsync();
        }
        
        if (_isAuthenticated != true) return null;
        
        try
        {
            return await _jsRuntime.InvokeAsync<string?>("localStorage.getItem", "google_token");
        }
        catch
        {
            return null;
        }
    }
}