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

[Route(Navigation.Management.HostGroups.Index)]
public partial class Index
{
    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;

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

    private IndexViewModel? Model { get; set; }

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

    private async Task<TableData<IndexViewModel>> 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 },
                                { "last_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.last_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",
                                10000
                            })
                    }))
                ))
                .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("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<IndexViewModel>()
            {
                TotalItems = countResult is null ? 0 : (int)countResult.Count,
                Items = itemResult.Select(x => BsonSerializer.Deserialize<IndexViewModel>(x))
            };
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
            return new TableData<IndexViewModel>();
        }
    }


    private bool _create;
    public bool Create
    {
        get
        {
            return _create;
        }
        set
        {
            if (value != _create)
            {
                _create = value;

                if (value)
                {
                    Model = new();
                }

                StateHasChanged();
            }
        }
    }

    private async Task OnCreateSubmitAsync()
    {
        try
        {
            await Database.Host()
                .InsertOneAsync(new HostEntity
                {
                    Name = Model?.Name,
                    Description = Model?.Description,
                }, cancellationToken: default);

            Container?.RefreshAsync();

            Notification.Success(Snackbar);
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
        }
        finally
        {
            Create = false;
        }
    }


    private bool _edit;
    public bool Edit
    {
        get
        {
            return _edit;
        }
        set
        {
            if (value != _edit)
            {
                _edit = value;
                StateHasChanged();

                Container?.RefreshAsync();
            }
        }
    }

    private void OnEdit(IndexViewModel model)
    {
        Model = model;
        Edit = true;
    }

    private async Task OnEditSubmitAsync()
    {
        try
        {
            await Database.Host()
                .UpdateOneAsync(Builders<HostEntity>
                .Filter
                .Eq(p => p.Id, Model?.Id?.ToString()), Builders<HostEntity>
                .Update
                .Set(p => p.Name, Model.Name)
                .Set(p => p.Description, Model.Description),
                cancellationToken: default);

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

            Notification.Success(Snackbar);
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
        }
        finally
        {
            Edit = false;
        }
    }


    private bool _delete;
    public bool Delete
    {
        get
        {
            return _delete;
        }
        set
        {
            if (value != _delete)
            {
                _delete = value;
                StateHasChanged();

                Container?.RefreshAsync();
            }
        }
    }

    private void OnDelete(IndexViewModel model)
    {
        Model = model;
        Delete = true;
    }

    private async Task OnDeleteSubmitAsync()
    {
        try
        {
            await Database.Host()
                .DeleteOneAsync(Builders<HostEntity>
                .Filter.Eq(p => p.Id, Model?.Id?.ToString()),
                cancellationToken: default);

            Notification.Success(Snackbar);
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
        }
        finally
        {
            Delete = false;
        }

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


    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 IndexViewModel
    {
        [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; }
    }
}