using Insight.Infrastructure.Services;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MudBlazor;
using System.ComponentModel.DataAnnotations;

namespace Insight.Web.Pages.Management.Accounts;

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

    [Inject] private IdentityService IdentityService { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private ILogger<AccountCreateDialog> Logger { get; init; } = default!;

    private IndexCreateDialogModel? Account { get; set; } = new();

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

        try
        {
            if (string.IsNullOrWhiteSpace(Account.Email) is false && Account.Email != Account.EmailConfirm)
            {
                Notification.Error(Snackbar, "Email not matching");
                return;
            }
            if (string.IsNullOrWhiteSpace(Account.Password) is false && Account.Password != Account.PasswordConfirm)
            {
                Notification.Error(Snackbar, "Password not matching");
                return;
            }

            var result = await IdentityService.CreateUserAsync(Account.Email, Account.Password);

            if (result.Succeeded is false)
            {
                throw new Exception(string.Concat(result.Errors));
            }

            Notification.Success(Snackbar);

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

public class IndexCreateDialogModel
{
    [Required, EmailAddress]
    public string? Email { get; set; }

    [Required, EmailAddress]
    public string? EmailConfirm { get; set; }

    [Required, DataType(DataType.Password)]
    public string? Password { get; set; }

    [Required, DataType(DataType.Password)]
    public string? PasswordConfirm { get; set; }
}