using Insight.Infrastructure;
using Insight.Infrastructure.Entities;
using Insight.Web.Components.Containers;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MongoDB.Bson;
using MongoDB.Driver;
using MudBlazor;
using System.Reflection.Metadata;
using System.Text.RegularExpressions;
using SortDirection = MudBlazor.SortDirection;

namespace Insight.Web.Pages.Management.Hosts.Systems.Updates;

[Route(Navigation.Management.Hosts.Systems.Updates.Pending.Index)]
public partial class Pending
{
    [Parameter] public string? HostId { 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<HostUpdateEntity>? Container { get; set; }
    private string Title { get; set; } = Global.Name;
    private List<BreadcrumbItem> Breadcrumbs { get; } = new();
    private string? Search { get; set; }

    private HostUpdateEntity? Selected { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (string.IsNullOrWhiteSpace(HostId) || ObjectId.TryParse(HostId, out var hostId) is false)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Index);
            return;
        }

        var host = await Database.Host()
            .Find(Builders<HostEntity>
            .Filter
            .Eq(p => p.Id, HostId))
            .FirstOrDefaultAsync(default);

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

        Title = $"Hosts » {host.Name} » Pending Updates｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Hosts", href: Navigation.Management.Hosts.Index));
        Breadcrumbs.Add(new BreadcrumbItem(host.Name, href: Navigation.Management.Hosts.DetailsHref(HostId)));
        Breadcrumbs.Add(new BreadcrumbItem("Pending Updates", href: "#", true));
    }

    private async Task<TableData<HostUpdateEntity>> LoadDataAsync(TableState state)
    {
        try
        {
            var filter = Builders<HostUpdateEntity>.Filter.Eq(x => x.Host, HostId);
            filter &= Builders<HostUpdateEntity>.Filter.Eq(x => x.Pending, true);

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<HostUpdateEntity>.Filter.Regex(x => x.Name, regex) |
                    Builders<HostUpdateEntity>.Filter.Regex(x => x.Description, regex) |
                    Builders<HostUpdateEntity>.Filter.Regex(x => x.SupportUrl, regex) |
                    Builders<HostUpdateEntity>.Filter.Regex(x => x.RebootBehavior, regex);
            }

            var query = Database.HostUpdate()
                .Find(filter)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Name" => Builders<HostUpdateEntity>.Sort.Ascending(p => p.Name),
                        "Description" => Builders<HostUpdateEntity>.Sort.Ascending(p => p.Description),
                        "SupportUrl" => Builders<HostUpdateEntity>.Sort.Ascending(p => p.SupportUrl),
                        "Downloaded" => Builders<HostUpdateEntity>.Sort.Ascending(p => p.IsDownloaded),
                        "RequestAction" => Builders<HostUpdateEntity>.Sort.Ascending(p => p.CanRequestUserInput),
                        "Reboot" => Builders<HostUpdateEntity>.Sort.Ascending(p => p.RebootBehavior),
                        "Date" => Builders<HostUpdateEntity>.Sort.Ascending(p => p.Date),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Name" => Builders<HostUpdateEntity>.Sort.Descending(p => p.Name),
                        "Description" => Builders<HostUpdateEntity>.Sort.Descending(p => p.Description),
                        "SupportUrl" => Builders<HostUpdateEntity>.Sort.Descending(p => p.SupportUrl),
                        "Downloaded" => Builders<HostUpdateEntity>.Sort.Descending(p => p.IsDownloaded),
                        "RequestAction" => Builders<HostUpdateEntity>.Sort.Descending(p => p.CanRequestUserInput),
                        "Reboot" => Builders<HostUpdateEntity>.Sort.Descending(p => p.RebootBehavior),
                        "Date" => Builders<HostUpdateEntity>.Sort.Descending(p => p.Date),
                        _ => null
                    },
                    _ => Builders<HostUpdateEntity>.Sort.Descending(p => p.Date)
                });

            return new TableData<HostUpdateEntity>()
            {
                TotalItems = (int)await query.CountDocumentsAsync(default),
                Items = await query.Skip(state.Page * state.PageSize).Limit(state.PageSize).ToListAsync(default)
            };
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
            return new TableData<HostUpdateEntity>();
        }
    }

    private void OnDescription(HostUpdateEntity model)
    {
        Selected = model;
        _detailsDialog?.Toggle();
    }
}