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

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

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

    private JobEntity? Model { get; set; }

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

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

        var task = await Database.Task()
            .Aggregate()
            .Match(Builders<TaskEntity>.Filter.Eq(p => p.Id, TaskId))
            .FirstOrDefaultAsync(default);

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

        Title = $"Scheduler » Tasks » {task.Name} » Jobs｜Insight";
        Breadcrumbs.Add(new BreadcrumbItem(task.Name, href: Navigation.Management.Scheduler.Tasks.DetailsHref(TaskId)));
        Breadcrumbs.Add(new BreadcrumbItem("Jobs", href: "#", true));
    }

    private async Task<TableData<JobEntity>> 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.JobTask()
                .Aggregate()
                .Match(Builders<JobTaskEntity>.Filter.Eq(p => p.Task, TaskId))
                .AppendStage<BsonDocument>(new BsonDocument("$lookup", new BsonDocument
                {
                    { "from", "job" },
                    { "localField", "_job" },
                    { "foreignField", "_id" },
                    { "as", "jobs" }
                }))
                .AppendStage<BsonDocument>(new BsonDocument("$addFields",
                    new BsonDocument("job", new BsonDocument("$first", "$jobs"))
                ))
                .AppendStage<BsonDocument>(new BsonDocument("$project", new BsonDocument
                {
                    { "_id", "$job._id" },
                    { "name", "$job.name" },
                    { "description", "$job.description" }
                }))
                .Match(filter)
                .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<JobEntity>()
            {
                TotalItems = countResult is null ? 0 : (int)countResult.Count,
                Items = itemResult.Select(x => BsonSerializer.Deserialize<JobEntity>(x))
            };
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
            return new TableData<JobEntity>();
        }
    }

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

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

        Unassign = true;
    }

    private async Task OnUnassignSubmitAsync()
    {
        try
        {
            await Database.JobTask()
                .DeleteOneAsync(Builders<JobTaskEntity>
                .Filter.And(Builders<JobTaskEntity>.Filter
                .Eq(p => p.Task, TaskId), Builders<JobTaskEntity>.Filter
                .Eq(p => p.Job, Model?.Id)),
                cancellationToken: default);

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

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