using DiunaBI.Application.DTOModels;
using DiunaBI.UI.Shared.Services;
using Microsoft.AspNetCore.Components;
using MudBlazor;
using System.Text;

namespace DiunaBI.UI.Shared.Pages.DataInbox;

public partial class Details : ComponentBase
{
    [Parameter]
    public Guid Id { get; set; }

    [Inject]
    private DataInboxService DataInboxService { get; set; } = null!;

    [Inject]
    private NavigationManager NavigationManager { get; set; } = null!;

    [Inject]
    private ISnackbar Snackbar { get; set; } = null!;

    private DataInboxDto? dataInbox;
    private string? decodedData;
    private bool hasDecodingError = false;
    private bool isLoading = false;

    protected override async Task OnInitializedAsync()
    {
        await LoadDataInbox();
    }

    protected override async Task OnParametersSetAsync()
    {
        await LoadDataInbox();
    }

    private async Task LoadDataInbox()
    {
        isLoading = true;
        StateHasChanged();

        try
        {
            dataInbox = await DataInboxService.GetDataInboxByIdAsync(Id);

            if (dataInbox != null)
            {
                DecodeData();
            }
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"Error loading data inbox: {ex.Message}");
            Snackbar.Add("Error loading data inbox item", Severity.Error);
        }
        finally
        {
            isLoading = false;
            StateHasChanged();
        }
    }

    private void DecodeData()
    {
        if (dataInbox == null || string.IsNullOrEmpty(dataInbox.Data))
        {
            decodedData = null;
            hasDecodingError = false;
            return;
        }

        try
        {
            var base64Bytes = Convert.FromBase64String(dataInbox.Data);
            decodedData = Encoding.UTF8.GetString(base64Bytes);
            hasDecodingError = false;
        }
        catch (Exception ex)
        {
            Console.Error.WriteLine($"Error decoding Base64 data: {ex.Message}");
            decodedData = null;
            hasDecodingError = true;
        }
    }

    private void GoBack()
    {
        NavigationManager.NavigateTo("/datainbox");
    }
}
