@namespace Oqtane.Modules.Admin.Users
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject IUserService UserService
@inject IProfileService ProfileService
@inject ISettingService SettingService
@inject IStringLocalizer<Add> Localizer

<TabStrip>
    <TabPanel Name="Identity" ResourceKey="Identity">
        @if (profiles != null)
        {
            <table class="table table-borderless">
                <tr>
                    <td>
                        <label class="control-label">@Localizer["Username:"] </label>
                    </td>
                    <td>
                        <input class="form-control" @bind="@username" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">@Localizer["Password:"] </label>
                    </td>
                    <td>
                        <input type="password" class="form-control" @bind="@password" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">@Localizer["Confirm Password:"] </label>
                    </td>
                    <td>
                        <input type="password" class="form-control" @bind="@confirm" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">@Localizer["Email:"] </label>
                    </td>
                    <td>
                        <input class="form-control" @bind="@email" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">@Localizer["Full Name:"] </label>
                    </td>
                    <td>
                        <input class="form-control" @bind="@displayname" />
                    </td>
                </tr>
            </table>
        }
    </TabPanel>
    <TabPanel Name="Profile" ResourceKey="Profile">
        @if (profiles != null)
        {
            <table class="table table-borderless">
                @foreach (Profile profile in profiles)
                {
                    var p = profile;
                    if (p.Category != category)
                    {
                        <tr>
                            <th colspan="2" style="text-align: center;">
                                @p.Category
                            </th>
                        </tr>
                        category = p.Category;
                    }
                    <tr>
                        <td>
                            <Label For="@p.Name" HelpText="@p.Description">@p.Title</Label>
                        </td>
                        <td>
                            @if (p.IsRequired)
                            {
                                <input id="@p.Name" class="form-control" maxlength="@p.MaxLength" value="@GetProfileValue(p.Name, p.DefaultValue)" required @onchange="@(e => ProfileChanged(e, p.Name))" />
                            }
                            else
                            {
                                <input id="@p.Name" class="form-control" maxlength="@p.MaxLength" value="@GetProfileValue(p.Name, p.DefaultValue)" @onchange="@(e => ProfileChanged(e, p.Name))" />
                            }
                        </td>
                    </tr>
                }
            </table>
        }
    </TabPanel>
</TabStrip>

<button type="button" class="btn btn-primary" @onclick="SaveUser">@Localizer["Save"]</button>
<NavLink class="btn btn-secondary" href="@NavigateUrl()">@Localizer["Cancel"]</NavLink>

@code {
    private string username = string.Empty;
    private string password = string.Empty;
    private string confirm = string.Empty;
    private string email = string.Empty;
    private string displayname = string.Empty;
    private List<Profile> profiles;
    private Dictionary<string, string> settings;
    private string category = string.Empty;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            profiles = await ProfileService.GetProfilesAsync(ModuleState.SiteId);
            settings = new Dictionary<string, string>();
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading User Profile {Error}", ex.Message);
            AddModuleMessage(Localizer["Error Loading User Profile"], MessageType.Error);
        }
    }

    private string GetProfileValue(string SettingName, string DefaultValue)
        => SettingService.GetSetting(settings, SettingName, DefaultValue);

    private async Task SaveUser()
    {
        try
        {
            if (username != string.Empty && password != string.Empty && confirm != string.Empty && email != string.Empty && ValidateProfiles())
            {
                if (password == confirm)
                {
                    var user = await UserService.GetUserAsync(username, PageState.Site.SiteId);
                    if (user == null)
                    {
                        user = new User();
                        user.SiteId = PageState.Site.SiteId;
                        user.Username = username;
                        user.Password = password;
                        user.Email = email;
                        user.DisplayName = string.IsNullOrWhiteSpace(displayname) ? username : displayname;
                        user.PhotoFileId = null;

                        user = await UserService.AddUserAsync(user);

                        if (user != null)
                        {
                            await SettingService.UpdateUserSettingsAsync(settings, user.UserId);
                            await logger.LogInformation("User Created {User}", user);
                            NavigationManager.NavigateTo(NavigateUrl());
                        }
                        else
                        {
                            await logger.LogError("Error Adding User {Username} {Email}", username, email);
                            AddModuleMessage(Localizer["Error Adding User. Please Ensure Password Meets Complexity Requirements And Username And Email Are Not Already In Use."], MessageType.Error);
                        }
                    }
                    else
                    {
                        AddModuleMessage(Localizer["Username Already Exists"], MessageType.Warning);
                    }
                }
                else
                {
                    AddModuleMessage(Localizer["Passwords Entered Do Not Match"], MessageType.Warning);
                }
            }
            else
            {
                AddModuleMessage(Localizer["You Must Provide A Username, Password, Email Address And All Required Profile Information"], MessageType.Warning);
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Adding User {Username} {Email} {Error}", username, email, ex.Message);
            AddModuleMessage(Localizer["Error Adding User"], MessageType.Error);
        }
    }

    private bool ValidateProfiles()
    {
        bool valid = true;
        foreach (Profile profile in profiles)
        {
            if (string.IsNullOrEmpty(SettingService.GetSetting(settings, profile.Name, string.Empty)) && !string.IsNullOrEmpty(profile.DefaultValue))
            {
                settings = SettingService.SetSetting(settings, profile.Name, profile.DefaultValue);
            }
            if (profile.IsRequired && string.IsNullOrEmpty(SettingService.GetSetting(settings, profile.Name, string.Empty)))
            {
                valid = false;
            }
        }
        return valid;
    }

    private void ProfileChanged(ChangeEventArgs e, string SettingName)
    {
        var value = (string)e.Value;
        settings = SettingService.SetSetting(settings, SettingName, value);
    }

}
