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.Text.RegularExpressions;
using SortDirection = MudBlazor.SortDirection;

namespace Insight.Web.Pages.Management.Customers;

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

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

    private TableContainer<CustomerEntity>? _container;
    private string _title = Global.Name;
    private string? _search;

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

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

            if (string.IsNullOrWhiteSpace(_search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(_search, RegexOptions.IgnoreCase));
                filter &= Builders<CustomerEntity>.Filter.Regex(x => x.Name, regex) |
                    Builders<CustomerEntity>.Filter.Regex(x => x.Tag, regex) |
                    Builders<CustomerEntity>.Filter.Regex(x => x.Hosts, regex);
            }

            var query = Database.Customer()
                .Aggregate()
                .Match(filter)
                .Lookup<CustomerEntity, HostEntity, CustomerEntity>(Database.Host(), p => p.Id, p => p.Customer, p => p.Hosts)
                .Sort(state.SortDirection switch
                {
                    SortDirection.Ascending => state.SortLabel switch
                    {
                        "Name" => Builders<CustomerEntity>.Sort.Ascending(p => p.Name),
                        "Tag" => Builders<CustomerEntity>.Sort.Ascending(p => p.Tag),
                        "Hosts" => Builders<CustomerEntity>.Sort.Ascending(p => p.Hosts),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Name" => Builders<CustomerEntity>.Sort.Descending(p => p.Name),
                        "Tag" => Builders<CustomerEntity>.Sort.Descending(p => p.Tag),
                        "Hosts" => Builders<CustomerEntity>.Sort.Descending(p => p.Hosts),
                        _ => null
                    },
                    _ => Builders<CustomerEntity>.Sort.Ascending(p => p.Name)
                });

            var countResult = await query.Count().FirstOrDefaultAsync(default);

            return new TableData<CustomerEntity>()
            {
                TotalItems = countResult is null ? 0 : (int)countResult.Count,
                Items = await query.Skip(state.Page * state.PageSize).Limit(state.PageSize).ToListAsync(default)
            };
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
            return new TableData<CustomerEntity>();
        }
    }

    private async Task OnRefreshAsync()
    {
        if (_container is null) return;
        await _container.RefreshAsync().ConfigureAwait(false);
    }
}