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

namespace Insight.Web.Pages.Management.HostGroups;

[Route(Navigation.Management.HostGroups.Hosts)]
public partial class Hosts
{
    [Parameter] public string? GroupId { 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;
    private string _title = Global.Name;
    private string? _search;
    private HostGroupEntity? _model;

    private readonly List<BreadcrumbItem> _breadcrumbs = new();

    protected override async Task OnInitializedAsync()
    {
        _breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        _breadcrumbs.Add(new BreadcrumbItem("Host Groups", href: Navigation.Management.HostGroups.Index));

        if (string.IsNullOrWhiteSpace(GroupId))
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.HostGroups.Index);
            return;
        }

        _model = await Database.HostGroup()
            .Aggregate()
            .Match(Builders<HostGroupEntity>.Filter.Eq(p => p.Id, GroupId))
            .FirstOrDefaultAsync(default);

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

        _title = $"Host Groups » {_model.Name} » Hosts｜Insight";

        _breadcrumbs.Add(new BreadcrumbItem(_model.Name, href: Navigation.Management.HostGroups.DetailsHref(GroupId)));
        _breadcrumbs.Add(new BreadcrumbItem("Hosts", href: "#", true));

        await InvokeAsync(StateHasChanged);
    }

    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);
            }

            var query = Database.HostGroupHost()
                .Aggregate()
                .Match(Builders<HostGroupHostEntity>.Filter.Eq(p => p.HostGroup, GroupId))
                .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 },
                    { "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"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Customer" => Builders<BsonDocument>.Sort.Descending("customer.name"),
                        "Host" => Builders<BsonDocument>.Sort.Descending("host.name"),
                        _ => null
                    },
                    _ => Builders<BsonDocument>.Sort.Ascending("customer.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>();
        }
    }

    private async Task OnUnassignAsync(string? hostId)
    {
        try
        {
            await Database.HostGroupHost()
                .DeleteOneAsync(Builders<HostGroupHostEntity>
                .Filter.Eq(p => p.Host, hostId), default);

            _container?.RefreshAsync();

            Notification.Success(Snackbar);
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
        }
        finally
        {
            NavigationManager?.NavigateTo(Navigation.Management.HostGroups.HostsHref(GroupId));
        }
    }

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

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