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.Hosts)]
public partial class Hosts
{
    [Parameter] public string? CustomerId { 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; }

    private HostEntity? Model { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (string.IsNullOrWhiteSpace(CustomerId))
        {
            Notification.Error(Snackbar, "Not Found");
            NavigationManager.NavigateTo(Navigation.Management.Customers.Index);
            return;
        }

        Breadcrumbs.Add(new BreadcrumbItem("Home", href: Navigation.Home));
        Breadcrumbs.Add(new BreadcrumbItem("Customers", href: Navigation.Management.Customers.Index));

        var customer = await Database.Customer()
            .Aggregate()
            .Match(Builders<CustomerEntity>.Filter.Eq(p => p.Id, CustomerId))
            .FirstOrDefaultAsync(default);

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

        Title = $"Customer » {customer.Name} » Hosts｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem(customer.Name, href: Navigation.Management.Customers.DetailsHref(CustomerId)));
        Breadcrumbs.Add(new BreadcrumbItem("Hosts", href: "#", true));
    }

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

            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.Description, regex) |
                    Builders<HostEntity>.Filter.Regex(x => x.Agents.First().Serial, regex);
            }

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

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

            return new TableData<HostEntity>()
            {
                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<HostEntity>();
        }
    }

    private void OnAdd()
    {
        NavigationManager.NavigateTo(Navigation.Management.Customers.HostsAssignHref(CustomerId));
    }

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

    private void OnUnassign(HostEntity model)
    {
        Model = new HostEntity
        {
            Id = model.Id,
            Name = model?.Name,
            Description = model?.Description
        };

        Unassign = true;
    }

    private async Task OnUnassignSubmitAsync()
    {
        try
        {
            await Database.Host()
                .UpdateOneAsync(Builders<HostEntity>
                .Filter
                .Eq(p => p.Id, Model.Id), Builders<HostEntity>
                .Update
                .Set(p => p.Customer, null),
                cancellationToken: default);

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

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