@page "/login"
@using System.Text.Json;
@using System.Text;
@using System.Net;
@using System.ComponentModel.DataAnnotations;
@using phronCare.UIBlazor.Models
@using phronCare.UIBlazor.Services.Authorization;
@using phronCare.UIBlazor.Models.Login;

@inject NavigationManager _navigationManager
@inject HttpClient _httpClient
@inject ILoginService _iLoginService
@inject IToastService toastService

<div class="row" style="margin-top: 30px;">
    <div class="col-md-3 col-sm-12" style="background-color: rgb(39, 54, 97); border-radius: 10px; color: white; padding: 20px; margin: 0 auto auto auto;">
                <img src="images/Logo.png" class="img-fluid" />
        @if (!isSecret)
            {
            <h3>Iniciar sesión</h3>
            <EditForm Model="login2FAModel" OnInvalidSubmit="LoginAsync">
                <div class="form-group">
                    <label>Usuario</label>
                    <div>
                        <InputText Class="form-control" @bind-Value=@login2FAModel.UserName />
                    </div>
                </div>

                <div class="form-group">
                    <label>Contraseña</label>
                    <div>
                        <InputText type="password" Class="form-control" @bind-Value=login2FAModel.Password />
                    </div>
                </div>
                @if (codeTwoFactor)
                {
                    <div class="form-group">
                        <label for="code">Código</label>
                        <InputText type="text" id="code" class="form-control" @bind-Value=login2FAModel.Code />
                    </div>
                }
                <br />
                <div class="col-12" style="text-align:center;">
                    <button type="submit" class="btn btn-primary" @onclick="LoginAsync">
                        <span class="fa fa-key"></span> Entrar</button>
                    <button class="btn btn-warning btn-circle" style="float:right;" @onclick="ToggleIsSecret">
                        <span class="fa fa-user-secret"></span>
                    </button>
                </div>
            </EditForm>
        }
        else
        {
            <h3>Restablecer password</h3>
            <EditForm Model="resetPassword" OnValidSubmit="ResetPasswordAsync">
                <DataAnnotationsValidator />
                <div class="form-group">
                    <label>Email</label>
                    <InputText @bind-Value="resetPassword.Email" class="form-control" />
                </div>
                <div class="form-group">
                    <label>Nueva Contraseña</label>
                    <InputText @bind-Value="resetPassword.Password" type="password" class="form-control" />
                </div>
                <div class="form-group">
                    <label>Confirmar Contraseña</label>
                    <InputText @bind-Value="resetPassword.ConfirmPassword" type="password" class="form-control" />
                </div>
                <div class="form-group">
                    <label>Token</label>
                    <InputTextArea @bind-Value="resetPassword.Token" class="form-control" />
                </div>
                <br/>
                <div class="col-12" style="text-align:center;">
                        <button type="submit" class="btn btn-primary"><span class="fa fa-vault"></span> Restablecer</button>
                        <button class="btn btn-warning btn-circle" style="fData.Login.Loginght;" @olick="ToggleIsSecret">
                      <span class="fa fa-circle-left"></span>
                        </button>
                </div>
            </EditForm>
        }
    </div>
</div>

@code {
    Login loginModel = new Login();
    Login2FA login2FAModel = new Login2FA();
    ResetPassword resetPassword = new ResetPassword();
    public bool isSecret = false;
    bool codeTwoFactor = false;
    string OTPCode = string.Empty;

    private async Task LoginAsync()
    {
        if (codeTwoFactor && login2FAModel.Code.Length > 4)
        {
            string requestUrl = $"api/Authentication/login-2FA?code={login2FAModel.Code}&username={login2FAModel.UserName}";
            var response = await _httpClient.PostAsync(requestUrl, null);
            if (response.IsSuccessStatusCode)
            {
                var tokenResponse = await response.Content.ReadAsStringAsync();

                await _iLoginService.Login(tokenResponse);

                _navigationManager.NavigateTo("/registration-confirmation");
            }
            else if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                var errorResponse = await response.Content.ReadAsStringAsync();
                var errorMessages = JsonSerializer.Deserialize<Response>(errorResponse);
            }
        }
        else
        {
            loginModel.UserName = login2FAModel.UserName;
            loginModel.Password = login2FAModel.Password;
            var jsonPayload = JsonSerializer.Serialize(loginModel);
            var requestContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync("api/Authentication/login", requestContent);
            if (response.StatusCode == HttpStatusCode.BadRequest)
            {
                var errors = await response.Content.ReadFromJsonAsync<Dictionary<string, List<string>>>();
            }
            else if (response.StatusCode == HttpStatusCode.OK)
            {
                var tokenResponse = await response.Content.ReadAsStringAsync();
                await _iLoginService.Login(tokenResponse);
            }
            else if (response.StatusCode == HttpStatusCode.Accepted)
            {
                codeTwoFactor = true;
            }
            else if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                var tokenResponse = await response.Content.ReadAsStringAsync();
                toastService.ShowError(tokenResponse);
            }
        }
    }
    private async Task ResetPasswordAsync()
    {
        if (resetPassword.Password != resetPassword.ConfirmPassword)
        {
            toastService.ShowError("Las contraseñas no coinciden. ¡Inténtalo de nuevo!");
        }
        else if (string.IsNullOrEmpty(resetPassword.Token))
        {
            toastService.ShowWarning("Debe ingresar el token enviado por correo.");
        }
        else
        {
            await ResetingPassword();
        }
    }
    private async Task ResetingPassword()
    {
        var jsonRequest = JsonSerializer.Serialize(resetPassword);
        var requestContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
        var response = await _httpClient.PostAsync("/api/Authentication/reset-password/", requestContent);
        var messageResponse = await response.Content.ReadAsStringAsync();
        if (response.IsSuccessStatusCode)
        {
            toastService.ShowSuccess(messageResponse);
            ToggleIsSecret();
            StateHasChanged();
        }
        else
        {
            toastService.ShowError(messageResponse);
        }
    }
    private void ToggleIsSecret()
    {
        isSecret = !isSecret;
    }
    #region Clases
    public class ResetPassword
    {
        [Required(ErrorMessage = "El campo Nueva Contraseña es obligatorio.")]
        public string Password { get; set; } = null!;
        [Compare("Password", ErrorMessage = "Las contraseñas no coinciden.")]
        public string ConfirmPassword { get; set; } = null!;
        [Required(ErrorMessage = "El campo Email es obligatorio.")]
        [EmailAddress(ErrorMessage = "El formato ingresado es invalido")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; } = null!;
        [Required(ErrorMessage = "El campo Token es obligatorio.")]
        public string Token { get; set; } = null!;
    }
    #endregion
}
