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

[Route(Navigation.Management.Hosts.CustomerAssign)]
public partial class CustomerAssign
{
    [Parameter] public string? HostId { 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<CustomerEntity>? 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(HostId) || ObjectId.TryParse(HostId, out var hostId) is false)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Hosts.Index);
            return;
        }

        var host = await Database.Host()
            .Aggregate()
            .Match(Builders<HostEntity>.Filter.Eq(p => p.Id, HostId))
            .Lookup<HostEntity, CustomerEntity, HostEntity>(Database.Customer(), p => p.Customer, p => p.Id, p => p.Customers)
            .FirstOrDefaultAsync(default);

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

        Title = $"Hosts » {host.Name} » Customer Assign｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Hosts", href: Navigation.Management.Hosts.Index));
        Breadcrumbs.Add(new BreadcrumbItem(host.Name, href: Navigation.Management.Hosts.DetailsHref(HostId)));
        Breadcrumbs.Add(new BreadcrumbItem("Customer Assign", href: "#", 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);
            }

            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),
                        _ => null
                    },
                    SortDirection.Descending => state.SortLabel switch
                    {
                        "Name" => Builders<CustomerEntity>.Sort.Descending(p => p.Name),
                        "Tag" => Builders<CustomerEntity>.Sort.Descending(p => p.Tag),
                        _ => 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 OnAssignAsync(CustomerEntity? model)
    {
        try
        {
            await Database.Host()
                .UpdateOneAsync(Builders<HostEntity>
                .Filter
                .Eq(p => p.Id, HostId), Builders<HostEntity>
                .Update
                .Set(p => p.Customer, model?.Id), cancellationToken: default);

            Container?.RefreshAsync();

            Notification.Success(Snackbar);
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
        }
        finally
        {
            NavigationManager?.NavigateTo(Navigation.Management.Hosts.DetailsHref(HostId));
        }
    }

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