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

[Route(Navigation.Management.Agents.HostAssign)]
public partial class HostAssign
{
    [Parameter] public string? AgentId { get; set; }

    [Inject] private IMongoDatabase Database { get; init; } = default!;
    [Inject] private ISnackbar Snackbar { get; init; } = default!;
    [Inject] private NavigationManager NavigationManager { get; init; } = default!;

    private TableContainer<HostEntity>? 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(AgentId) || ObjectId.TryParse(AgentId, out var agentId) is false)
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Agents.Index);
            return;
        }

        var agent = await Database.Agent()
            .Aggregate()
            .Match(Builders<AgentEntity>.Filter.Eq(p => p.Id, AgentId))
            .Lookup<AgentEntity, HostEntity, AgentEntity>(Database.Host(), p => p.Id, p => p.Agent, p => p.Hosts)
            .FirstOrDefaultAsync(default);

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

        Title = $"Agent » {agent.Hostname} » Assign Host｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Agents", href: Navigation.Management.Agents.Index));
        Breadcrumbs.Add(new BreadcrumbItem(agent.Hostname, href: Navigation.Management.Agents.DetailsHref(AgentId)));
        Breadcrumbs.Add(new BreadcrumbItem("Assign", href: "#", true));
    }

    private async Task<TableData<HostEntity>> LoadDataAsync(TableState state)
    {
        try
        {
            var filter = Builders<HostEntity>.Filter.Eq(p => p.Agent, null);

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<HostEntity>.Filter.Regex(x => x.Name, regex) |
                    Builders<HostEntity>.Filter.Regex(x => x.Customers.First().Name, regex);
            }

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

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

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

    private async Task OnAssignAsync(HostEntity? model)
    {
        try
        {
            await Database.Host()
                .UpdateOneAsync(Builders<HostEntity>
                .Filter
                .Eq(p => p.Id, model?.Id), Builders<HostEntity>
                .Update
                .Set(p => p.Agent, AgentId), cancellationToken: default);

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

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