using Insight.Infrastructure;
using Insight.Infrastructure.Entities;
using Insight.Web.Components.Containers;
using Insight.Web.Constants;
using Insight.Web.Extensions;
using Microsoft.AspNetCore.Components;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using MudBlazor;
using System.Text.RegularExpressions;
using SortDirection = MudBlazor.SortDirection;

namespace Insight.Web.Pages.Inventory.Systems.Users;

[Route(Navigation.Inventory.Systems.Users.Hosts)]
public partial class Hosts
{
    [Parameter] public string? UserName { get; set; }

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

    private TableContainer<ViewModel>? Container { get; set; }
    private string Title { get; set; } = Global.Name;
    private List<BreadcrumbItem> Breadcrumbs { get; } = new();
    private string? Search { get; set; }

    protected override void OnInitialized()
    {
        UserName = UserName?.UriEscape(true);

        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Inventory", href: "#", true));
        Breadcrumbs.Add(new BreadcrumbItem("Users", href: Navigation.Inventory.Systems.Users.Index));

        if (string.IsNullOrWhiteSpace(UserName))
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Inventory.Systems.Users.Index);
            return;
        }

        Title = $"Inventory » Users » {UserName} » Hosts｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem(UserName, href: "#", true));
        Breadcrumbs.Add(new BreadcrumbItem("Hosts", href: "#", true));
    }

    private async Task<TableData<ViewModel>> LoadDataAsync(TableState state)
    {
        try
        {
            var filter = Builders<BsonDocument>.Filter.Empty;

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<BsonDocument>.Filter.Regex("customer.name", regex) |
                    Builders<BsonDocument>.Filter.Regex("host.name", regex) |
                    Builders<BsonDocument>.Filter.Regex("domain", regex) |
                    Builders<BsonDocument>.Filter.Regex("localaccount", regex) |
                    Builders<BsonDocument>.Filter.Regex("disabled", regex) |
                    Builders<BsonDocument>.Filter.Regex("status", regex);
            }

            var query = Database.HostSystemUser()
                .Aggregate()
                .Match(Builders<HostUserEntity>.Filter.Eq(p => p.Name, UserName))
                .Lookup("host", "_host", "_id", "hosts")
                .Match(new BsonDocument("hosts", new BsonDocument
                {
                    { "$exists", true },
                    { "$ne", new BsonArray() }
                }))
                .Lookup("customer", "hosts._customer", "_id", "customers")
                .Project(new BsonDocument
                {
                    { "_id", 0 },
                    { "domain", 1 },
                    { "localaccount", 1 },
                    { "disabled", 1 },
                    { "status", 1 },
                    { "host", new BsonDocument("$first", "$hosts") },
                    { "customer", new BsonDocument("$first", "$customers") },
                })
                .Match(filter)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Customer" => Builders<BsonDocument>.Sort.Ascending("customer.name"),
                        "Host" => Builders<BsonDocument>.Sort.Ascending("host.name"),
                        "Domain" => Builders<BsonDocument>.Sort.Ascending("domain"),
                        "LocalAccount" => Builders<BsonDocument>.Sort.Ascending("localaccount"),
                        "Disabled" => Builders<BsonDocument>.Sort.Ascending("disabled"),
                        "Status" => Builders<BsonDocument>.Sort.Ascending("status"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Customer" => Builders<BsonDocument>.Sort.Descending("customer.name"),
                        "Host" => Builders<BsonDocument>.Sort.Descending("host.name"),
                        "Domain" => Builders<BsonDocument>.Sort.Descending("domain"),
                        "LocalAccount" => Builders<BsonDocument>.Sort.Descending("localaccount"),
                        "Disabled" => Builders<BsonDocument>.Sort.Descending("disabled"),
                        "Status" => Builders<BsonDocument>.Sort.Descending("status"),
                        _ => null
                    },
                    _ => Builders<BsonDocument>.Sort.Ascending("host.name")
                });

            var countResult = await query.Count().FirstOrDefaultAsync(default);
            var itemResult = await query.Skip(state.Page * state.PageSize).Limit(state.PageSize).ToListAsync(default);

            return new TableData<ViewModel>()
            {
                TotalItems = countResult is null ? 0 : (int)countResult.Count,
                Items = itemResult.Select(x => BsonSerializer.Deserialize<ViewModel>(x))
            };
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
            return new TableData<ViewModel>();
        }
    }

    [BsonIgnoreExtraElements]
    public class ViewModel
    {
        [BsonElement("domain")]
        public string? Domain { get; set; }

        [BsonElement("localaccount")]
        public bool? LocalAccount { get; set; }

        [BsonElement("disabled")]
        public bool? Disabled { get; set; }

        [BsonElement("status")]
        public string? Status { get; set; }

        [BsonElement("host")]
        public HostEntity? Hosts { get; set; }

        [BsonElement("customer")]
        public CustomerEntity? Customers { get; set; }
    }
}