@using AliasVault.Shared.Models.Spamok
@using AliasVault.Shared.Utilities
@inject JsInteropService JsInteropService
@inject GlobalNotificationService GlobalNotificationService
@inject IHttpClientFactory HttpClientFactory
@inject HttpClient HttpClient

<ClickOutsideHandler OnClose="OnClose" ContentId="emailModal">
    <div class="fixed inset-0 z-50 overflow-auto bg-gray-500 bg-opacity-75 flex items-center justify-center">
        <div id="emailModal" class="relative p-8 bg-white w-3/4 flex-col flex rounded-lg shadow-xl">
            <div class="flex items-center justify-between">
                <h2 class="text-2xl font-bold text-gray-900">
                    @if (IsSpamOk)
                    {
                        <a target="_blank" href="https://spamok.com/@(Email!.ToLocal)/@(Email!.Id)">@Email.Subject</a>
                    }
                    else
                    {
                        <span>@Email?.Subject</span>
                    }
                </h2>
                <button @onclick="Close" class="text-gray-400 hover:text-gray-500">
                    <svg class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>
            <div class="mt-4">
                <p class="text-sm text-gray-500 dark:text-gray-400">From: @(Email?.FromLocal)@@@(Email?.FromDomain)</p>
                <p class="text-sm text-gray-500 dark:text-gray-400">To: @(Email?.ToLocal)@@@(Email?.ToDomain)</p>
                <p class="text-sm text-gray-500 dark:text-gray-400">Date: @Email?.DateSystem</p>
            </div>
            <div class="mt-4 text-gray-700 dark:text-gray-300">
                <div>
                    <iframe class="w-full overscroll-y-auto" style="height:500px;" srcdoc="@EmailBody">
                    </iframe>
                </div>
            </div>
            <div class="mt-6 flex justify-end space-x-4">
                <button id="delete-email" @onclick="DeleteEmail" class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600">Delete</button>
                <button id="close-email-modal" @onclick="Close" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">Close</button>
            </div>
        </div>
    </div>
</ClickOutsideHandler>

@code {
    /// <summary>
    /// The email to show in the modal.
    /// </summary>
    [Parameter]
    public EmailApiModel? Email { get; set; }

    /// <summary>
    /// Boolean that indicates if the email is from SpamOK public API.
    /// </summary>
    [Parameter]
    public bool IsSpamOk { get; set; }

    /// <summary>
    /// Callback when the modal is closed.
    /// </summary>
    [Parameter]
    public EventCallback<bool> OnClose { get; set; }

    /// <summary>
    /// Callback when an email is deleted.
    /// </summary>
    [Parameter]
    public EventCallback<int> OnEmailDeleted { get; set; }

    /// <summary>
    /// The message body to display
    /// </summary>
    private string EmailBody = string.Empty;

    /// <summary>
    /// Close the modal.
    /// </summary>
    [JSInvokable]
    public Task Close()
    {
        return OnClose.InvokeAsync(false);
    }

    /// <summary>
    /// Delete the current email.
    /// </summary>
    private async Task DeleteEmail()
    {
        if (Email == null)
        {
            return;
        }

        if (IsSpamOk)
        {
            await DeleteEmailSpamOk();
        }
        else
        {
            await DeleteEmailAliasVault();
        }
    }

    /// <summary>
    /// Delete the current email in SpamOk.
    /// </summary>
    private async Task DeleteEmailSpamOk()
    {
        if (Email == null)
        {
            return;
        }

        try
        {
            var client = HttpClientFactory.CreateClient("EmailClient");
            var response = await client.DeleteAsync($"https://api.spamok.com/v2/Email/{Email.ToLocal}/{Email.Id}");
            if (response.IsSuccessStatusCode)
            {
                GlobalNotificationService.AddSuccessMessage("Email deleted successfully", true);
                await OnEmailDeleted.InvokeAsync(Email.Id);
                await Close();
            }
            else
            {
                var errorMessage = await response.Content.ReadAsStringAsync();
                GlobalNotificationService.AddErrorMessage($"Failed to delete email: {errorMessage}", true);
            }
        }
        catch (Exception ex)
        {
            GlobalNotificationService.AddErrorMessage($"An error occurred: {ex.Message}", true);
        }
    }

    /// <summary>
    /// Delete the current email in AliasVault.
    /// </summary>
    private async Task DeleteEmailAliasVault()
    {
        if (Email == null)
        {
            return;
        }

        try
        {
            var response = await HttpClient.DeleteAsync($"v1/Email/{Email.Id}");
            if (response.IsSuccessStatusCode)
            {
                GlobalNotificationService.AddSuccessMessage("Email deleted successfully", true);
                await OnEmailDeleted.InvokeAsync(Email.Id);
                await Close();
            }
            else
            {
                var errorMessage = await response.Content.ReadAsStringAsync();
                GlobalNotificationService.AddErrorMessage($"Failed to delete email: {errorMessage}", true);
            }
        }
        catch (Exception ex)
        {
            GlobalNotificationService.AddErrorMessage($"An error occurred: {ex.Message}", true);
        }
    }

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        // Determine email body
        if (Email != null)
        {
            // Check if there is HTML content, if not, then set default viewtype to plain
            if (Email.MessageHtml is not null && !string.IsNullOrWhiteSpace(Email.MessageHtml))
            {
                // HTML is available
                EmailBody = ConversionUtility.ConvertAnchorTagsToOpenInNewTab(Email.MessageHtml);
            }
            else if (Email.MessagePlain is not null)
            {
                // No HTML but plain text is available
                EmailBody = Email.MessagePlain;
            }
            else
            {
                // No HTML and no plain text available
                EmailBody = "[This email has no body.]";
            }
        }
    }
}
