@page "/login"
@using System.Web
@using System.Collections.Specialized
@using Blazored.LocalStorage
@using Blazored.SessionStorage
@using BlazorPolicyAuth.App.Services.AuthService
@using BlazorPolicyAuth.Models.ViewModels
@inject IAuthService AuthService
@inject ILocalStorageService LocalStorageService
@inject ISessionStorageService SessionStorageService
@inject NavigationManager NavigationManager
@inject AuthenticationStateProvider AuthenticationStateProvider

<PageTitle>Login</PageTitle>

<div class="d-flex justify-content-center align-items-center">
    <div class="col-md-4 p-5 shadow-sm border rounded-3">
        <h2 class="text-center mb-4 text-primary">Login Form</h2>
        <EditForm Model="user" OnValidSubmit="HandleLogin" FormName="loginForm">
            <DataAnnotationsValidator />
            <div class="mb-3">
                <label for="email">Email</label>
                <InputText id="email" @bind-Value="user.Email" class="form-control border border-primary" />
                <ValidationMessage For="@(() => user.Email)" />
            </div>
            <div class="mb-3">
                <label for="password">Password</label>
                <InputText id="password" @bind-Value="user.Password" class="form-control border border-primary" type="password" />
                <ValidationMessage For="@(() => user.Password)" />
            </div>
            <div class="mb-3">
                <label for="rememberme">Remember me</label>
                <InputCheckbox id="rememberme" @bind-Value="rememberMe"  class="form-check-input" />
            </div>
            <div class="d-grid">
                <button type="submit" class="btn btn-primary">Login</button>
            </div>
            <div class="mt-3">
                <a href="#">Forgot password</a>
            </div>
            <div class="mt-3">
                <p class="mb-0 text-center">You don't have an account? <a href="register" class="text-primary fw-bold">Register</a></p>
            </div>
        </EditForm>
    </div>
</div>
<div class="text-danger">
    <span>@errorMessage</span>
</div>

@code {
    [SupplyParameterFromForm] private UserLogin user { get; set; }
    private string errorMessage = string.Empty;
    private string returnUrl = string.Empty;
    private bool rememberMe;
    
    protected override void OnInitialized()
    {
        user ??= new();
        var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
        NameValueCollection queryStringCall = HttpUtility.ParseQueryString(uri.Query);

        if (queryStringCall.AllKeys.Contains("returnUrl"))
        {
            returnUrl = queryStringCall["returnUrl"];
        }
    }

    private async Task HandleLogin()
    {
        var result = await AuthService.Login(user);
        if (result.Success)
        {
            errorMessage = string.Empty;
            if (rememberMe)
                await LocalStorageService.SetItemAsync("authToken", result.Data);
            else
                await SessionStorageService.SetItemAsync("authToken", result.Data);

            await AuthenticationStateProvider.GetAuthenticationStateAsync();
            NavigationManager.NavigateTo(returnUrl);
        }
        else
        {
            errorMessage = result.Message;
        }
    }
}