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.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 TableContainer<CustomerEntity>? Container { get; set; }
    private string Title { get; set; } = Global.Name;
    private List<BreadcrumbItem> Breadcrumbs { get; } = new();
    private string? Search { get; set; }

    private CustomerEntity? Model { get; set; }

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

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

    private void OnEdit(CustomerEntity model)
    {
        Model = new CustomerEntity
        {
            Id = model.Id,
            Insert = model?.Insert,
            Update = model?.Update,
            Name = model?.Name,
            Tag = model?.Tag
        };

        _editDialog?.Toggle();
    }

    private void OnDelete(CustomerEntity model)
    {
        Model = new CustomerEntity
        {
            Id = model.Id,
            Insert = model?.Insert,
            Update = model?.Update,
            Name = model?.Name,
            Tag = model?.Tag
        };

        _deleteDialog?.Toggle();
    }
}