@page "/admin/users/edit/{Id:int}"
@using Moonlight.App.Repositories
@using Moonlight.App.Database.Entities
@using Moonlight.App.Models.Forms
@using Moonlight.App.Models.Misc
@using Moonlight.App.Services
@using Moonlight.App.Services.Interop
@using Moonlight.App.Services.Sessions
@using Mappy.Net

@inject Repository<User> UserRepository
@inject Repository<PermissionGroup> PermissionGroupRepository
@inject UserService UserService
@inject SessionServerService SessionServerService
@inject ToastService ToastService
@inject SmartTranslateService SmartTranslateService

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

<LazyLoader Load="Load">
    @if (User == null)
    {
        <div class="alert alert-danger">
            <TL>No user with this id found</TL>
        </div>
    }
    else
    {
        <div class="card">
            <div class="card-header border-0 py-0">
                <h3 class="card-title align-items-start flex-column">
                    <span class="card-label fw-bold fs-3">
                        <TL>Manage user </TL> <span class="text-primary">@(User.Email)</span>
                    </span>
                </h3>
            </div>
        </div>

        <SmartForm Model="Model" OnValidSubmit="Update">
            <div class="mt-5 row">
                <div class="col-xl-6 mb-5 mb-xl-10">
                    <div class="card card-body p-10">
                        <div class="mb-10">
                            <label class="form-label">
                                <TL>First name</TL>
                            </label>
                            <InputText @bind-Value="Model.FirstName" class="form-control"/>
                        </div>
                        <div class="mb-10">
                            <label class="form-label">
                                <TL>Last name</TL>
                            </label>
                            <InputText @bind-Value="Model.LastName" class="form-control"/>
                        </div>
                        <div class="mb-10">
                            <label class="form-label">
                                <TL>Email</TL>
                            </label>
                            <InputText @bind-Value="Model.Email" type="email" class="form-control"/>
                        </div>
                    </div>
                    <div class="mt-5 card card-body p-10">
                        <div class="input-group">
                            <select @bind="User.Status" class="form-select">
                                @foreach (var status in (UserStatus[])Enum.GetValues(typeof(UserStatus)))
                                {
                                    if (User.Status == status)
                                    {
                                        <option value="@(status)" selected="">@(status)</option>
                                    }
                                    else
                                    {
                                        <option value="@(status)">@(status)</option>
                                    }
                                }
                            </select>
                            <WButton Text="@(SmartTranslateService.Translate("Change"))"
                                     WorkingText="@(SmartTranslateService.Translate("Reloading"))"
                                     CssClasses="btn-primary"
                                     OnClick="UpdateStatus">
                            </WButton>
                        </div>
                    </div>
                    <div class="mt-5 card card-body p-10">
                        <div class="input-group">
                            <input @bind="NewPassword" type="password" class="form-control" placeholder="@(SmartTranslateService.Translate("Password"))"/>
                            <WButton Text="@(SmartTranslateService.Translate("Change"))"
                                     WorkingText="@(SmartTranslateService.Translate("Reloading"))"
                                     CssClasses="btn-primary"
                                     OnClick="ChangePassword">
                            </WButton>
                        </div>
                    </div>
                    <div class="mt-5 card card-body p-10">
                        <div class="input-group">
                            <SmartDropdown T="PermissionGroup"
                                           @bind-Value="Model.PermissionGroup"
                                           Items="PermissionGroups"
                                           DisplayFunc="@(x => x.Name)"
                                           SearchProp="@(x => x.Name)">
                            </SmartDropdown>
                        </div>
                    </div>
                    <div class="mt-5 card card-body p-10">
                        <div class="d-flex justify-content-end">
                            <a href="/admin/users" class="btn btn-danger me-3">
                                <TL>Cancel</TL>
                            </a>
                            <WButton Text="@(SmartTranslateService.Translate("Edit permissions"))"
                                     CssClasses="btn-primary me-3"
                                     OnClick="EditPermissions">
                            </WButton>
                            <button type="submit" class="btn btn-success">
                                <TL>Update</TL>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="col-xl-6 mb-5 mb-xl-10">
                    <div class="card card-body p-10">
                        <div class="mb-10">
                            <label class="form-label">
                                <TL>Address</TL>
                            </label>
                            <InputText @bind-Value="Model.Address" class="form-control"/>
                        </div>
                        <div class="mb-10">
                            <label class="form-label">
                                <TL>City</TL>
                            </label>
                            <InputText @bind-Value="Model.City" class="form-control"/>
                        </div>
                        <div class="mb-10">
                            <label class="form-label">
                                <TL>State</TL>
                            </label>
                            <InputText @bind-Value="Model.State" class="form-control"/>
                        </div>
                        <div class="mb-10">
                            <label class="form-label">
                                <TL>Country</TL>
                            </label>
                            <InputText @bind-Value="Model.Country" class="form-control"/>
                        </div>
                        <div class="mb-10">
                            <input @bind="Model.TotpEnabled" type="checkbox" class="form-check-input">
                            <label class="form-label">
                                <TL>Totp</TL>
                            </label>
                        </div>
                        <div class="mb-10">
                            <input @bind="Model.Admin" type="checkbox" class="form-check-input">
                            <label class="form-label">
                                <TL>Admin</TL>
                            </label>
                        </div>
                    </div>
                    <div class="mt-5 card card-body p-10">
                        <div class="mb-10">
                            <label class="form-label">
                                <TL>Discord id</TL>
                            </label>

                            <input @bind="Model.DiscordId" type="number" class="form-control">
                        </div>
                    </div>
                </div>
            </div>
        </SmartForm>
    }

    <PermissionEditor @ref="PermissionEditor" OnSave="SavePermissions"/>
</LazyLoader>

@code
{
    [Parameter]
    public int Id { get; set; }

    private User? User;
    private UserEditDataModel Model { get; set; } = new();
    private string NewPassword = "";

    private PermissionGroup[] PermissionGroups;

    private PermissionEditor PermissionEditor;

    private Task Load(LazyLoader arg)
    {
        User = UserRepository.Get().FirstOrDefault(x => x.Id == Id);

        if (User != null)
        {
            Model = Mapper.Map<UserEditDataModel>(User);
            PermissionGroups = PermissionGroupRepository
                .Get()
                .ToArray();
        }

        return Task.CompletedTask;
    }

    private async Task UpdateStatus()
    {
        var user = UserRepository.Get().FirstOrDefault(x => x.Id == User!.Id)!;
        user.Status = User!.Status;
        UserRepository.Update(user);

        await SessionServerService.ReloadUserSessions(User);

        await ToastService.Success(SmartTranslateService.Translate("Successfully updated user"));
    }

    private async Task Update()
    {
        User = Mapper.Map(User, Model);
        UserRepository.Update(User!);

        await ToastService.Success(SmartTranslateService.Translate("Successfully updated user"));
    }

    private async Task ChangePassword()
    {
        await UserService.ChangePassword(User!, NewPassword, true);
        NewPassword = "";

        await SessionServerService.ReloadUserSessions(User!);

        await ToastService.Success(SmartTranslateService.Translate("Successfully updated password"));
    }

    private async Task EditPermissions()
    {
        PermissionEditor.InitialData = User!.Permissions;
        await PermissionEditor.Launch();
    }

    private async Task SavePermissions(byte[] data)
    {
        User!.Permissions = data;
        UserRepository.Update(User);

        await SessionServerService.ReloadUserSessions(User);

        await ToastService.Success(SmartTranslateService.Translate("Successfully updated user"));
    }
}