@page "/admin/domains/new"
@using Moonlight.App.Services
@using Moonlight.App.Database.Entities
@using Moonlight.App.Models.Forms
@using Moonlight.App.Repositories
@using Moonlight.App.Repositories.Domains

@inject SmartTranslateService SmartTranslateService
@inject SharedDomainRepository SharedDomainRepository
@inject UserRepository UserRepository
@inject NavigationManager NavigationManager
@inject DomainService DomainService

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

<div class="row mb-5">
        <div class="card card-body p-10">
            <LazyLoader Load="Load">
                <SmartForm Model="Model" OnValidSubmit="Add">
                    <label class="form-label">
                        <TL>Domain name</TL>
                    </label>
                    <div class="input-group mb-5">
                        <span class="input-group-text">
                            <i class="bx bx-purchase-tag-alt"></i>
                        </span>
                        <InputText @bind-Value="Model.Name" class="form-control" placeholder="@(SmartTranslateService.Translate("Domain name"))"></InputText>
                    </div>
                    <div class="mb-5">
                        <label class="form-label">
                            <TL>Shared domain</TL>
                        </label>
                        <SmartSelect @bind-Value="Model.SharedDomain"
                                     Items="SharedDomains"
                                     DisplayField="@(x => x.Name)">
                        </SmartSelect>
                    </div>
                    <div class="input-group mb-5">
                        <SmartDropdown @bind-Value="Model.Owner"
                                       Items="Users"
                                       DisplayFunc="@(x => x.Email)"
                                       SearchProp="@(x => x.Email)">
                        </SmartDropdown>
                    </div>
                    <button class="btn btn-success" type="submit">
                        <TL>Create</TL>
                    </button>
                </SmartForm>
            </LazyLoader>
        </div>
    </div>

@code
{
    private DomainDataModel Model = new();

    private User[] Users;
    private SharedDomain[] SharedDomains;

    private Task Load(LazyLoader lazyLoader)
    {
        Users = UserRepository.Get().ToArray();
        SharedDomains = SharedDomainRepository.Get().ToArray();

        return Task.CompletedTask;
    }

    private async Task Add()
    {
        await DomainService.Create(Model.Name, Model.SharedDomain, Model.Owner);

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