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.HostsAssign)]
public partial class HostAssign
{
    [Parameter] public string? GroupId { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { 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 async Task OnInitializedAsync()
    {
        if (string.IsNullOrWhiteSpace(GroupId) || ObjectId.TryParse(GroupId, out var groupId) is false)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.HostGroups.Index);
            return;
        }

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

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

        Title = $"Host Groups » {hostgroup.Name} » Hosts » Assign｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Host Groups", href: Navigation.Management.HostGroups.Index));
        Breadcrumbs.Add(new BreadcrumbItem(hostgroup.Name, href: Navigation.Management.HostGroups.DetailsHref(GroupId)));
        Breadcrumbs.Add(new BreadcrumbItem("Hosts", href: Navigation.Management.HostGroups.HostsHref(GroupId)));
        Breadcrumbs.Add(new BreadcrumbItem("Assign", href: "#", true));
    }

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

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                search &= Builders<BsonDocument>.Filter.Regex("customerName", regex) |
                Builders<BsonDocument>.Filter.Regex("hostName", regex);
            }

            var query = Database.Host()
                .Aggregate()
                .AppendStage<BsonDocument>(new BsonDocument("$lookup", new BsonDocument
                {
                    { "from", "hostgroup_host" },
                    { "localField", "_id" },
                    { "foreignField", "_host" },
                    { "as", "map" }
                }))
                .AppendStage<BsonDocument>(new BsonDocument("$project", new BsonDocument
                {
                    { "_id", 0 },
                    { "hostId", "$_id" },
                    { "hostName", "$name" },
                    { "customerId", "$_customer" },
                    { "hostgroup", new BsonDocument("$first", "$map._hostgroup") }
                }))
                .AppendStage<BsonDocument>(
                    new BsonDocument("$match",
                    new BsonDocument("hostgroup", new BsonDocument("$ne", new ObjectId(GroupId))))
                )
                .AppendStage<BsonDocument>(new BsonDocument("$lookup", new BsonDocument
                {
                    { "from", "customer" },
                    { "localField", "customerId" },
                    { "foreignField", "_id" },
                    { "as", "customerName" }
                }))
                .AppendStage<BsonDocument>(new BsonDocument("$addFields",
                    new BsonDocument("customerName", new BsonDocument("$first", "$customerName.name"))))
                .Match(search)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Customer" => Builders<BsonDocument>.Sort.Ascending("customer.name"),
                        "Name" => Builders<BsonDocument>.Sort.Ascending("name"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Customer" => Builders<BsonDocument>.Sort.Descending("customer.name"),
                        "Name" => Builders<BsonDocument>.Sort.Descending("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 ex)
        {
            Console.WriteLine(ex.ToString());

            Notification.Error(Snackbar);
            return new TableData<ViewModel>();
        }
    }

    private async Task OnAssignAsync(string? hostId)
    {
        try
        {
            await Database.HostGroupHost()
                .InsertOneAsync(new HostGroupHostEntity
                {
                    Insert = DateTime.Now,
                    HostGroup = GroupId,
                    Host = hostId
                }, null, default);

            Container?.RefreshAsync();

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

    [BsonIgnoreExtraElements]
    public class ViewModel
    {
        [BsonElement("customerId"), BsonRepresentation(BsonType.ObjectId)]
        public string? CustomerId { get; set; }

        [BsonElement("customerName")]
        public string? CustomerName { get; set; }

        [BsonElement("hostId"), BsonRepresentation(BsonType.ObjectId)]
        public string? HostId { get; set; }

        [BsonElement("hostName")]
        public string? HostName { get; set; }
    }
}