@page "/registration"
@using System.Text.Json
@using System.ComponentModel.DataAnnotations

@inject HttpClient httpClient
@inject IToastService toastService
@inject NavigationManager navigation

<div class="card mt-4" style="zoom:90%">
    <div class="card-header text-center">
        <h3 class="card-title">Registro de Usuario</h3>
    </div>

    <div class="card-body">
        <EditForm Model="user" OnValidSubmit="RegistrarUsuario">
            <DataAnnotationsValidator />
            <ValidationSummary />

            <div class="row">
                <div class="col-md-6">
                    <label for="InputUserName">Nombre de Usuario:</label>
                    <InputText id="InputUserName" @bind-Value="user.UserName" class="form-control" />
                </div>
                <div class="col-md-6">
                    <label for="InputEmail">Correo Electrónico:</label>
                    <InputText id="InputEmail" @bind-Value="user.EmailAddress" class="form-control" />
                </div>
            </div>

            <div class="row mt-3">
                <div class="col-md-6">
                    <label for="InputPassword">Contraseña:</label>
                    <InputText id="InputPassword" @bind-Value="user.Password" type="password" class="form-control" />
                </div>
                <div class="col-md-6">
                    <label for="InputConfirmPassword">Confirmar Contraseña:</label>
                    <InputText id="InputConfirmPassword" @bind-Value="confirmPassword" type="password" class="form-control" />
                </div>
            </div>

            <div class="row mt-3">
                <div class="col-md-6">
                    <label for="InputRole">Rol:</label>
                    <InputSelect @bind-Value="user.Role" class="form-control">
                        @foreach (var role in roles)
                        {
                            <option value="@role.Name">@role.Name</option>
                        }
                    </InputSelect>
                </div>
                <div class="col-md-6">
                    <label for="PhoneNumber">Teléfono:</label>
                    <InputText id="PhoneNumber" @bind-Value="user.PhoneNumber" class="form-control" />
                </div>
            </div>

            <div class="row mt-3">
                <div class="col-md-6">
                    <label for="FirstName">Nombre:</label>
                    <InputText id="FirstName" @bind-Value="user.FirstName" class="form-control" />
                </div>
                <div class="col-md-6">
                    <label for="LastName">Apellido:</label>
                    <InputText id="LastName" @bind-Value="user.LastName" class="form-control" />
                </div>
            </div>

            <div class="row mt-3">
                <div class="col-md-6">
                    <label for="Company">Empresa:</label>
                    <InputText id="Company" @bind-Value="user.CompanyName" class="form-control" />
                </div>
                <div class="col-md-6">
                    <label for="Department">Departamento:</label>
                    <InputText id="Department" @bind-Value="user.Department" class="form-control" />
                </div>
            </div>

            <div class="row mt-3">
                <div class="col-md-6">
                    <label for="BirthDate">Fecha de nacimiento:</label>
                    <InputDate id="BirthDate" @bind-Value="user.BirthDate" class="form-control" />
                </div>
            </div>
        </EditForm>
    </div>

    <div class="card-footer d-flex justify-content-end">
        <button type="submit" class="btn btn-primary me-2" @onclick="RegistrarUsuario">Registrar</button>
        <button type="button" class="btn btn-secondary" @onclick="Cancel">Cancelar</button>
    </div>
</div>

@code {
    private User user = new();
    private string confirmPassword = string.Empty;

    public List<Role> roles = new();

    private const int USERNAME_VALID_LENGTH = 8;

    protected override async Task OnInitializedAsync()
    {
        roles = await GetAllRoles();
    }

    private async Task<List<Role>> GetAllRoles()
    {
        var response = await httpClient.GetFromJsonAsync<List<Role>>("/api/Account/GetAllRoles");
        return response ?? new List<Role>();
    }

    private async Task RegistrarUsuario()
    {
        if (user.UserName.Length < USERNAME_VALID_LENGTH)
        {
            toastService.ShowError($"El nombre de usuario debe tener al menos {USERNAME_VALID_LENGTH} caracteres.");
        }
        else if (user.Password != confirmPassword)
        {
            toastService.ShowError("Las contraseñas no coinciden.");
        }
        else if (string.IsNullOrEmpty(user.Role))
        {
            toastService.ShowWarning("Debe seleccionar un rol.");
        }
        else
        {
            await CreateUser();
        }
    }

    private async Task CreateUser()
    {
        var requestContent = new StringContent(JsonSerializer.Serialize(user), System.Text.Encoding.UTF8, "application/json");
        var response = await httpClient.PostAsync("/api/Authentication/register/", requestContent);
        var errorResponse = await response.Content.ReadAsStringAsync();
        if (response.IsSuccessStatusCode)
        {
            toastService.ShowSuccess(errorResponse);
            navigation.NavigateTo("/users");
        }
        else
        {
            toastService.ShowError(errorResponse);
        }
    }

    private void Cancel()
    {
        navigation.NavigateTo("/users");
    }

    public class User
    {
        [Required] public string UserName { get; set; } = string.Empty;
        [EmailAddress, Required] public string EmailAddress { get; set; } = string.Empty;
        [Required] public string Password { get; set; } = string.Empty;
        [Required] public string Role { get; set; } = string.Empty;
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
        public string? PhoneNumber { get; set; }
        public string? CompanyName { get; set; }
        public string? Department { get; set; }
        public DateTime? BirthDate { get; set; }
    }

    public class Role
    {
        public string Id { get; set; } = string.Empty;
        public string Name { get; set; } = string.Empty;
        public string NormalizedName { get; set; } = string.Empty;
        public string ConcurrencyStamp { get; set; } = string.Empty;
    }
}
