@page "/account/manage"
@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Identity

@inject UserManager<AdminUser> UserManager

<LayoutPageTitle>Profile</LayoutPageTitle>

<div class="max-w-2xl mx-auto">
    <h3 class="text-2xl font-bold text-gray-900 dark:text-white mb-6">Profile</h3>

    <EditForm Model="Input" FormName="profile" OnValidSubmit="OnValidSubmitAsync" class="space-y-6">
        <DataAnnotationsValidator/>
        <ValidationSummary class="text-red-600 dark:text-red-400" role="alert"/>
        <div>
            <label for="username" class="block mb-2 text-sm font-medium text-gray-700 dark:text-gray-200">Username</label>
            <input type="text" value="@username" id="username" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 bg-gray-100 cursor-not-allowed dark:bg-gray-700 dark:border-gray-600 dark:text-gray-400" placeholder="Please choose your username." disabled/>
        </div>
        <div>
            <label for="phone-number" class="block mb-2 text-sm font-medium text-gray-700 dark:text-gray-200">Phone number</label>
            <InputText @bind-Value="Input.PhoneNumber" id="phone-number" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary-500 focus:border-primary-500 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white" placeholder="Please enter your phone number."/>
            <ValidationMessage For="() => Input.PhoneNumber" class="mt-1 text-sm text-red-600 dark:text-red-400"/>
        </div>
        <div>
            <SubmitButton>Save</SubmitButton>
        </div>
    </EditForm>
</div>

@code {
    private string? username;
    private string? phoneNumber;

    [SupplyParameterFromForm] private InputModel Input { get; set; } = new();

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        username = await UserManager.GetUserNameAsync(UserService.User());
        phoneNumber = await UserManager.GetPhoneNumberAsync(UserService.User());

        Input.PhoneNumber ??= phoneNumber;
    }

    private async Task OnValidSubmitAsync()
    {
        if (Input.PhoneNumber != phoneNumber)
        {
            var setPhoneResult = await UserManager.SetPhoneNumberAsync(UserService.User(), Input.PhoneNumber);
            if (!setPhoneResult.Succeeded)
            {
                GlobalNotificationService.AddErrorMessage("Phone number could not be set", true);
            }
        }

        GlobalNotificationService.AddSuccessMessage("Your profile has been updated", true);
    }

    private sealed class InputModel
    {
        [Phone]
        [Display(Name = "Phone number")]
        public string? PhoneNumber { get; set; }
    }

}
