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.Tasks)]
public partial class Tasks
{
    [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<TaskEntity>? Container { get; set; }
    private string Title { get; set; } = Global.Name;
    private List<BreadcrumbItem> Breadcrumbs { get; } = new();
    private string? Search { get; set; }

    private TaskEntity? 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;
        }

        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));

        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;
        }

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

    private async Task<TableData<TaskEntity>> 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.Job, JobId))
                .AppendStage<BsonDocument>(new BsonDocument("$lookup", new BsonDocument
                {
                    { "from", "task" },
                    { "localField", "_task" },
                    { "foreignField", "_id" },
                    { "as", "tasks" }
                }))
                .AppendStage<BsonDocument>(new BsonDocument("$addFields",
                    new BsonDocument("task", new BsonDocument("$first", "$tasks"))
                ))
                .AppendStage<BsonDocument>(new BsonDocument("$project", new BsonDocument
                {
                    { "_id", "$task._id" },
                    { "name", "$task.name" },
                    { "description", "$task.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<TaskEntity>()
            {
                TotalItems = countResult is null ? 0 : (int)countResult.Count,
                Items = itemResult.Select(x => BsonSerializer.Deserialize<TaskEntity>(x))
            };
        }
        catch (Exception)
        {
            Notification.Error(Snackbar);
            return new TableData<TaskEntity>();
        }
    }

    private void OnAdd()
    {
        NavigationManager.NavigateTo(Navigation.Management.Scheduler.Jobs.TasksAssignHref(JobId));
    }

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

    private void OnUnassign(TaskEntity model)
    {
        Model = new TaskEntity
        {
            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.Job, JobId), Builders<JobTaskEntity>.Filter
                .Eq(p => p.Task, Model?.Id)),
                cancellationToken: default);

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

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