@page "/settings/vault"
@inherits MainBase
@inject CredentialService CredentialService
@inject ILogger<Vault> Logger

<LayoutPageTitle>Vault settings</LayoutPageTitle>

<PageHeader
    BreadcrumbItems="@BreadcrumbItems"
    Title="Vault settings"
    Description="On this page you can configure your vault settings.">
</PageHeader>

<div class="p-4 mx-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">
    <h3 class="mb-4 text-xl font-semibold dark:text-white">Export vault</h3>
    <div class="mb-4">
        <div class="p-4 mb-4 text-sm text-yellow-800 rounded-lg bg-yellow-50 dark:bg-yellow-900 dark:text-yellow-100">
            <p><strong>Warning:</strong> Exporting your vault to an unencrypted file will expose all of your passwords and sensitive information in plain text. Only do this on trusted computers and ensure you:</p>
            <ul class="list-disc ml-6 mt-2">
                <li>Store the exported file in a secure location</li>
                <li>Delete the file when you no longer need it</li>
                <li>Never share the exported file with others</li>
            </ul>
        </div>
        <div>
            <Button OnClick="ExportVaultSqlite">Export vault to unencrypted SQLite file</Button>
        </div>
        <div class="mt-6">
            <Button OnClick="ExportVaultCsv">Export vault to unencrypted CSV file</Button>
        </div>
    </div>
</div>

<div class="p-4 mx-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">
    <h3 class="mb-4 text-xl font-semibold dark:text-white">Import vault</h3>
    <div class="mb-4">
        <div class="text-gray-900 dark:text-white">
            Import unencrypted CSV file:
            <InputFile class="dark:text-white" OnChange="@LoadFiles" />
        </div>
    </div>
</div>

@if (IsImporting)
{
    <p>Loading...</p>
}
else if (!string.IsNullOrEmpty(ImportErrorMessage))
{
    <p class="text-danger">@ImportErrorMessage</p>
}
else if (!string.IsNullOrEmpty(ImportSuccessMessage))
{
    <p class="text-success">@ImportSuccessMessage</p>
}

@code {
    private bool IsImporting;
    private string ImportErrorMessage = string.Empty;
    private string ImportSuccessMessage = string.Empty;

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        BreadcrumbItems.Add(new BreadcrumbItem { DisplayName = "Vault settings" });
    }

    private async Task ExportVaultSqlite()
    {
        try
        {
            // Decode the base64 string to a byte array.
            byte[] fileBytes = Convert.FromBase64String(await DbService.ExportSqliteToBase64Async());

            // Create a memory stream from the byte array.
            using (MemoryStream memoryStream = new MemoryStream(fileBytes))
            {
                // Invoke JavaScript to initiate the download.
                await JsInteropService.DownloadFileFromStream("aliasvault-client.sqlite", memoryStream.ToArray());
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "Error downloading file");
        }
    }

    private async Task ExportVaultCsv()
    {
        try
        {
            var credentials = await CredentialService.LoadAllAsync();

            var csvBytes = CsvImportExport.CredentialCsvService.ExportCredentialsToCsv(credentials);

            // Create a memory stream from the byte array.
            using (MemoryStream memoryStream = new MemoryStream(csvBytes))
            {
                // Invoke JavaScript to initiate the download.
                await JsInteropService.DownloadFileFromStream("aliasvault-client.csv", memoryStream.ToArray());
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "Error downloading file");
        }
    }

    private async Task LoadFiles(InputFileChangeEventArgs e)
    {
        IsImporting = true;
        StateHasChanged();
        ImportErrorMessage = string.Empty;
        ImportSuccessMessage = string.Empty;

        try
        {
            var file = e.File;
            var buffer = new byte[file.Size];
            var bytesRead = await file.OpenReadStream().ReadAsync(buffer);
            if (bytesRead != file.Size)
            {
                throw new FileLoadException("Error reading file");
            }

            var fileContent = System.Text.Encoding.UTF8.GetString(buffer);
            var importedCredentials = CsvImportExport.CredentialCsvService.ImportCredentialsFromCsv(fileContent);

            // Loop through the imported credentials and actually add them to the database.
            foreach (var importedCredential in importedCredentials)
            {
                await CredentialService.InsertEntryAsync(importedCredential, false);
            }

            // Save the database.
            await DbService.SaveDatabaseAsync();

            ImportSuccessMessage = $"Successfully imported {importedCredentials.Count} credentials.";
        }
        catch (Exception ex)
        {
            ImportErrorMessage = $"Error importing file: {ex.Message}";
        }
        finally
        {
            IsImporting = false;
            StateHasChanged();
        }
    }
}
