using Insight.Infrastructure.Entities;
using Insight.Infrastructure.Services;
using Insight.Web.Constants;
using Insight.Web.Extensions;
using Insight.Web.Middleware;
using Insight.Web.Models.Account;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Identity;
using MudBlazor;

namespace Insight.Web.Pages.Account;

[Route(Navigation.Account.Login)]
[Route(Navigation.Account.LoginTFA)]
public partial class Login
{
    [Parameter] public Guid? Key { get; set; }

    [Inject] private UserManager<InsightUser> UserManager { get; init; } = default!;
    [Inject] private IdentityService IdentityService { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;

    private readonly string _title = "Login｜Insight";

    private async Task SubmitAsync(LoginModel model)
    {
        if (string.IsNullOrWhiteSpace(model.Email))
        {
            Notification.Error(Snackbar, "Invalid E-Mail");
            return;
        }

        if (string.IsNullOrWhiteSpace(model.Password))
        {
            Notification.Error(Snackbar, "Invalid Password");
            return;
        }

        var user = await IdentityService.GetByEmailAsync(model.Email).ConfigureAwait(false);
        if (user is null || user.LockoutEnabled && user.LockoutEnd > DateTime.UtcNow || await UserManager.CheckPasswordAsync(user, model.Password) is false)
        {
            Notification.Error(Snackbar, "Access denied");
            return;
        }

        var query = NavigationManager.GetQueryString();
        if (query.TryGetValue("redirect", out var redirect))
        {
            model.Redirect = redirect;
        }

        IdentityMiddleware.Logins[model.Key] = model;
        NavigationManager.NavigateTo(Navigation.Account.SignInHref(model.Key), true);
    }

    private void SubmitTwoFactor(string? code)
    {
        if (string.IsNullOrWhiteSpace(code))
        {
            Notification.Information(Snackbar, "Enter Authenticator Code");
            return;
        }

        try
        {
            IdentityMiddleware.Logins[Key.Value].TwoFactorToken = code;
            NavigationManager.NavigateTo(Navigation.Account.SignInTFAHref(Key.Value), true);
        }
        catch (Exception ex)
        {
            Notification.Error(Snackbar, "Invalid Security Token");
            NavigationManager.NavigateTo(Navigation.Account.LoginHref(null), false);
        }
    }
}