@page "/login"
@using System.Security.Claims
@using BlazorPolicyAuth.Data
@using BlazorPolicyAuth.Models.ViewModels
@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Authentication.Cookies
@using Microsoft.EntityFrameworkCore
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject NavigationManager NavigationManager
@inject IAuthService AuthService

<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="userLogin" OnValidSubmit="Authenticate" FormName="LoginForm">
            <DataAnnotationsValidator />
            <div class="mb-3">
                <label for="email">User Name</label>
                <InputText id="email" @bind-Value="userLogin.UserName" class="form-control border border-primary" />
                <ValidationMessage For="@(() => userLogin.UserName)" />
            </div>
            <div class="mb-3">
                <label for="password">Password</label>
                <InputText id="password" @bind-Value="userLogin.Password" class="form-control border border-primary" type="password" />
                <ValidationMessage For="@(() => userLogin.Password)" />
            </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>


@code {
    // [CascadingParameter]
    // public HttpContext? HttpContext { get; set; }

    // [SupplyParameterFromForm] 
    // public LoginViewModel Model { get; set; } = new();

    private UserLogin userLogin = new();
    private string? _errorMessage;

    private async Task Authenticate()
    {
        Console.WriteLine("***");
        Console.WriteLine(userLogin.UserName);
        var result = await AuthService.Login(userLogin.UserName, userLogin.Password);
        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);
            NavigationManager.NavigateTo("/");
        }
        else
        {
            _errorMessage = result.Message;
        }
        // if(string.IsNullOrWhiteSpace(Model.UserName) || string.IsNullOrWhiteSpace(Model.Password))
        // {
        //     _errorMessage = "Invalid User Name or Password";
        //     return;
        // }

        // var userAccount = DbContext.UserAccounts.FirstOrDefault(x => x.UserName == Model.UserName);
        // if (userAccount is null || userAccount.Password != Model.Password)
        // {
        //     _errorMessage = "Invalid User Name or Password";
        //     return;
        // }

        // var claims = new List<Claim>
        // {
        //     new Claim(ClaimTypes.Name, Model.UserName)
        // };

        // /* Add Policies */
        // var userAccountPolicies = await DbContext.UserAccountPolicies.Where(x => x.UserAccountId == userAccount.Id && x.IsEnabled).ToListAsync();
        // claims.AddRange(userAccountPolicies.Select(userAccountPolicy => new Claim(userAccountPolicy.UserPolicy, "true")));

        // var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        // var principal = new ClaimsPrincipal(identity);
        // await HttpContext?.SignInAsync(principal)!;
        // NavigationManager.NavigateTo("/");
    }
}