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.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.Hosts;

[Route(Navigation.Management.Hosts.Index)]
public partial class Index
{
    [Inject] private IMongoDatabase Database { 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; }

    private ViewModel? Model { get; set; }

    protected override void OnInitialized()
    {
        Title = "Hosts｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Hosts", href: Navigation.Management.Hosts.Index, true));
    }

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

            if (FilterUnassignedCustomer)
            {
                filter &= Builders<HostEntity>.Filter.Eq(p => p.Customer, null);
            }

            if (FilterUnassignedAgent)
            {
                filter &= Builders<HostEntity>.Filter.Eq(p => p.Agent, null);
            }

            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("name", regex) |
                    Builders<BsonDocument>.Filter.Regex("description", regex) |
                    Builders<BsonDocument>.Filter.Regex("customer.name", regex) |
                    Builders<BsonDocument>.Filter.Regex("agent.serial", regex);
            }

            var query = Database.Host()
                .Aggregate()
                .Match(filter)
                .AppendStage<BsonDocument>(new BsonDocument("$lookup", new BsonDocument
                {
                    { "from", "agent" },
                    { "localField", "_agent" },
                    { "foreignField", "_id" },
                    { "pipeline", new BsonArray
                        {
                            new BsonDocument("$project", new BsonDocument
                            {
                                { "serial", 1 },
                                { "activity", 1 }
                            })
                        }
                    },
                    { "as", "agents" }
                }))
                .AppendStage<BsonDocument>(new BsonDocument("$lookup", new BsonDocument
                {
                    { "from", "customer" },
                    { "localField", "_customer" },
                    { "foreignField", "_id" },
                    { "pipeline", new BsonArray
                        {
                            new BsonDocument("$project",
                            new BsonDocument("name", 1))
                        }
                    },
                    { "as", "customers" }
                }))
                .AppendStage<BsonDocument>(new BsonDocument("$project", new BsonDocument
                {
                    { "name", 1 },
                    { "description", 1 },
                    { "agent", new BsonDocument("$first", "$agents") },
                    { "customer", new BsonDocument("$first", "$customers") }
                }))
                .AppendStage<BsonDocument>(new BsonDocument("$addFields",
                    new BsonDocument("online_diff",
                    new BsonDocument("$subtract", new BsonArray
                    {
                        DateTime.Now,
                        "$agent.activity"
                    }))
                ))
                .AppendStage<BsonDocument>(new BsonDocument("$addFields",
                    new BsonDocument("online",
                    new BsonDocument("$and", new BsonArray
                    {
                        new BsonDocument("$cond",
                        new BsonArray
                        {
                            new BsonDocument("$isNumber",
                            new BsonArray
                            {
                                "$online_diff"
                            }), 1, 0
                        }), new BsonDocument("$lt",
                            new BsonArray
                            {
                                "$online_diff",
                                60000
                            })
                    }))
                ))
                .Match(search)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Name" => Builders<BsonDocument>.Sort.Ascending("name"),
                        "Customer" => Builders<BsonDocument>.Sort.Ascending("customer.name"),
                        "Agent" => Builders<BsonDocument>.Sort.Ascending("agent.serial"),
                        "Online" => Builders<BsonDocument>.Sort.Ascending("online"),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Name" => Builders<BsonDocument>.Sort.Descending("name"),
                        "Customer" => Builders<BsonDocument>.Sort.Descending("customer.name"),
                        "Agent" => Builders<BsonDocument>.Sort.Descending("agent.serial"),
                        "Online" => Builders<BsonDocument>.Sort.Descending("online"),
                        _ => 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 OnRefreshAsync()
    {
        if (Container is null) return;
        await Container.RefreshAsync().ConfigureAwait(false);
    }

    private void OnCreate()
    {
        _createDialog?.Toggle();
    }

    private void OnEdit(ViewModel model)
    {
        Model = new ViewModel
        {
            Id = model.Id,
            Name = model?.Name,
            Description = Model?.Description
        };

        _editDialog?.Toggle();
    }

    private void OnDelete(ViewModel model)
    {
        Model = new ViewModel
        {
            Id = model.Id,
            Name = model?.Name,
            Description = Model?.Description
        };

        _deleteDialog?.Toggle();
    }

    private bool _filter;
    private bool Filter
    {
        get
        {
            return _filter;
        }
        set
        {
            if (value != _filter)
            {
                _filter = value;
                StateHasChanged();
            }
        }
    }

    private bool Filtered => FilterUnassignedCustomer || FilterUnassignedAgent;

    private bool _filterUnassignedCustomer;
    public bool FilterUnassignedCustomer
    {
        get
        {
            return _filterUnassignedCustomer;
        }
        set
        {
            if (value != _filterUnassignedCustomer)
            {
                _filterUnassignedCustomer = value;

                Container?.RefreshAsync();

                if (value)
                {
                    Notification.Warning(Snackbar, "Filtered");
                }
            }
        }
    }

    private bool _filterUnassignedAgent;
    public bool FilterUnassignedAgent
    {
        get
        {
            return _filterUnassignedAgent;
        }
        set
        {
            if (value != _filterUnassignedAgent)
            {
                _filterUnassignedAgent = value;

                if (Container is not null)
                {
                    _ = Container.RefreshAsync();
                }

                if (value)
                {
                    Notification.Warning(Snackbar, "Filtered");
                }
            }
        }
    }

    private void OnFilterReset()
    {
        FilterUnassignedCustomer = false;
        FilterUnassignedAgent = false;
    }
}

[BsonIgnoreExtraElements]
public class ViewModel
{
    [BsonId]
    public ObjectId? Id { get; set; }

    [BsonElement("name")]
    public string? Name { get; set; }

    [BsonElement("description")]
    public string? Description { get; set; }

    [BsonElement("agent")]
    public AgentEntity? Agent { get; set; }

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

    [BsonElement("online")]
    public bool Online { get; set; }
}