using Insight.Infrastructure.Entities;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MongoDB.Bson;
using MongoDB.Driver;
using MudBlazor;

namespace Insight.Web.Pages.Management.Accounts;

public partial class AccountEditDialog
{
    [Parameter] public EventCallback OnChanges { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private ILogger<AccountEditDialog> Logger { get; init; } = default!;

    private InsightUser? _model;

    public async void ToggleAsync(string? id)
    {
        if (id is null) return;

        try
        {
            _model = await Database.User().Find(p => p.Id == new ObjectId(id)).FirstAsync();
            _visible = !_visible;
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
        }

        await InvokeAsync(StateHasChanged);
    }

    private async Task SubmitAsync()
    {
        if (_model is null) return;

        try
        {
            await Database.User()
                .UpdateOneAsync(Builders<InsightUser>
                .Filter
                .Eq(p => p.Id, _model.Id), Builders<InsightUser>
                .Update
                .Set(p => p.Email, _model.Email)
                .Set(p => p.NormalizedEmail, _model.Email.ToUpperInvariant())
                .Set(p => p.UserName, _model.Email)
                .Set(p => p.NormalizedUserName, _model.Email.ToUpperInvariant()),
                cancellationToken: default);

            Notification.Success(Snackbar);

            if (OnChanges.HasDelegate)
            {
                await InvokeAsync(async () =>
                {
                    await OnChanges.InvokeAsync(this);
                });
            }
        }
        catch (Exception ex)
        {
            Notification.Error(Snackbar);
            Logger.LogError(ex.ToString());
        }
        finally
        {
            _visible = false;
        }
    }
}