using Insight.Infrastructure;
using Insight.Infrastructure.Entities;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MongoDB.Bson;
using MongoDB.Driver;
using MudBlazor;

namespace Insight.Web.Pages.Management.Accounts;

[Route(Navigation.Management.Accounts.Details)]
public partial class Details
{
    [Parameter] public string? AccountId { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;

    private string _title = Global.Name;
    private readonly List<BreadcrumbItem> _breadcrumbs = new();
    private readonly DetailsModel _model = new();

    private async Task LoadDataAsync()
    {
        _breadcrumbs.Clear();

        if (string.IsNullOrWhiteSpace(AccountId) || ObjectId.TryParse(AccountId, out var accountId) is false)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Accounts.Index);
            return;
        }

        _breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        _breadcrumbs.Add(new BreadcrumbItem("Accounts", href: Navigation.Management.Accounts.Index));

        StateHasChanged();

        var user = await Database.User()
                .Find(Builders<InsightUser>
                .Filter.Eq(p => p.Id, accountId))
                .FirstOrDefaultAsync(default);

        if (user is null)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Accounts.Index);
            return;
        }

        _model.Username = user.UserName;
        _model.Email = user.Email;
        _model.TwoFactorEnabled = user.TwoFactorEnabled;
        _model.Roles = user.Roles;

        _title = $"Accounts » {user.UserName}｜Insight";
        _breadcrumbs.Add(new BreadcrumbItem(user.UserName, href: "#", true));

        await InvokeAsync(StateHasChanged);
    }
}

public class DetailsModel
{
    public string? Username { get; set; }
    public string? Email { get; set; }
    public bool TwoFactorEnabled { get; set; }
    public List<ObjectId>? Roles { get; set; }
}