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? _model;

    public async Task ToggleAsync()
    {
        _model = new();
        _visible = !_visible;

        await InvokeAsync(StateHasChanged);
    }

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

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

            var result = await IdentityService.CreateUserAsync(_model.Email, _model.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
        {
            _model = 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; }
}