@page "/admin/webspaces/new"

@using Moonlight.App.Models.Forms
@using Moonlight.App.Services
@using Moonlight.App.Database.Entities
@using Moonlight.App.Repositories

@inject WebSpaceService WebSpaceService
@inject UserRepository UserRepository
@inject NavigationManager NavigationManager

@attribute [PermissionRequired(nameof(Permissions.AdminNewWebspace))]

<div class="card card-body p-10">
    <LazyLoader Load="Load">
        <SmartForm Model="Model" OnValidSubmit="OnValidSubmit">
            <label class="form-label">
                <TL>Base domain</TL>
            </label>
            <div class="input-group mb-5">
                <InputText @bind-Value="Model.BaseDomain" class="form-control"></InputText>
            </div>
            <label class="form-label">
                <TL>Owner</TL>
            </label>
            <div class="input-group mb-5">
                <SmartDropdown @bind-Value="Model.User"
                               Items="Users"
                               DisplayFunc="@(x => x.Email)"
                               SearchProp="@(x => x.Email)">
                </SmartDropdown>
            </div>
            <div>
                <button type="submit" class="btn btn-primary float-end">
                    <TL>Create</TL>
                </button>
            </div>
        </SmartForm>
    </LazyLoader>
</div>

@code
{
    private WebsiteAdminDataModel Model = new();
    private User[] Users;

    private async Task OnValidSubmit()
    {
        await WebSpaceService.Create(Model.BaseDomain, Model.User);

        NavigationManager.NavigateTo("/admin/webspaces");
    }

    private Task Load(LazyLoader arg)
    {
        Users = UserRepository
            .Get()
            .ToArray();

        return Task.CompletedTask;
    }
}