using Insight.Infrastructure.Entities;
using Insight.Web.Components.Containers;
using Insight.Web.Constants;
using Microsoft.AspNetCore.Components;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MudBlazor;
using System.Text.RegularExpressions;
using SortDirection = MudBlazor.SortDirection;

namespace Insight.Web.Pages.Management.Scheduler.Jobs;

[Route(Navigation.Management.Scheduler.Jobs.TriggersAssign)]
public partial class TriggersAssign
{
    [Parameter] public string? JobId { 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<TriggerEntity>? Container { get; set; }
    private string Title { get; set; } = Global.Name;
    private List<BreadcrumbItem> Breadcrumbs { get; } = new();
    private string? Search { get; set; }

    private TriggerEntity? Model { get; set; }

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

        var job = await Database.Job()
            .Aggregate()
            .Match(Builders<JobEntity>.Filter.Eq(p => p.Id, JobId))
            .FirstOrDefaultAsync(default);

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

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

        Title = $"Scheduler » Jobs » {job.Name} » Assign Triggers｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem(job.Name, href: Navigation.Management.Scheduler.Jobs.DetailsHref(JobId)));
        Breadcrumbs.Add(new BreadcrumbItem("Triggers", href: Navigation.Management.Scheduler.Jobs.TriggersHref(JobId)));
        Breadcrumbs.Add(new BreadcrumbItem("Assign", href: "#", true));
    }

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

            if (string.IsNullOrWhiteSpace(Search) is false)
            {
                var regex = new BsonRegularExpression(new Regex(Search, RegexOptions.IgnoreCase));
                filter &= Builders<BsonDocument>.Filter.Regex("name", regex) |
                    Builders<BsonDocument>.Filter.Regex("description", regex);
            }

            var query = Database.Trigger()
                .Aggregate()
                .AppendStage<BsonDocument>(new BsonDocument("$lookup", new BsonDocument
                {
                    { "from", "job_triggers" },
                    { "localField", "_id" },
                    { "foreignField", "_trigger" },
                    { "as", "map" }
                }))
                .AppendStage<BsonDocument>(new BsonDocument("$unwind", new BsonDocument
                {
                    { "path", "$map" },
                    { "preserveNullAndEmptyArrays", true }
                }))
                .AppendStage<BsonDocument>(
                    new BsonDocument("$match", 
                    new BsonDocument("map._job", new BsonDocument("$ne", new ObjectId(JobId))))
                )
                .Sort(state.SortDirection switch
                 {
                     SortDirection.Ascending => state.SortLabel switch
                     {
                         "Name" => Builders<BsonDocument>.Sort.Ascending("name"),
                         "Description" => Builders<BsonDocument>.Sort.Ascending("description"),
                         _ => null
                     },
                     SortDirection.Descending => state.SortLabel switch
                     {
                         "Name" => Builders<BsonDocument>.Sort.Descending("name"),
                         "Description" => Builders<BsonDocument>.Sort.Descending("description"),
                         _ => null
                     },
                     _ => Builders<BsonDocument>.Sort.Ascending("name")
                 });

            var countResult = await query.Count().FirstOrDefaultAsync(default);
            var itemResult = await query.Skip(state.Page * state.PageSize).Limit(state.PageSize).ToListAsync(default);

            return new TableData<TriggerEntity>()
            {
                TotalItems = countResult is null ? 0 : (int)countResult.Count,
                Items = itemResult.Select(x => BsonSerializer.Deserialize<TriggerEntity>(x))
            };
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
            return new TableData<TriggerEntity>();
        }
    }


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

    private void OnAssign(TriggerEntity? model)
    {
        Model = model;
        Assign = true;
    }

    private async Task OnAddSubmitAsync()
    {
        try
        {
            await Database.JobTrigger()
                .InsertOneAsync(new JobTriggerEntity
                {
                    Job = JobId,
                    Trigger = Model.Id
                }, cancellationToken: default);

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

            Notification.Success(Snackbar);
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
        }
        finally
        {
            Assign = false;
            NavigationManager?.NavigateTo(Navigation.Management.Scheduler.Jobs.TriggersHref(JobId));
        }
    }
}