@using AliasVault.RazorComponents.Tables
@using AliasVault.Shared.Models.Enums
@inherits MainBase

<div class="mb-4">
    <Paginator CurrentPage="CurrentPage" PageSize="PageSize" TotalRecords="TotalRecords" OnPageChanged="HandlePageChanged" />

    <SortableTable Columns="@_tableColumns" SortColumn="@SortColumn" SortDirection="@SortDirection" OnSortChanged="HandleSortChanged">
        @foreach (var job in JobList)
        {
            <SortableTableRow>
                <SortableTableColumn IsPrimary="true">@job.Id</SortableTableColumn>
                <SortableTableColumn>@job.RunDate.ToString("yyyy-MM-dd")</SortableTableColumn>
                <SortableTableColumn>@job.StartTime.ToString("HH:mm")</SortableTableColumn>
                <SortableTableColumn>@(job.EndTime?.ToString("HH:mm") ?? "-")</SortableTableColumn>
                <SortableTableColumn>
                    @{
                        string bgColor = job.Status switch
                        {
                            TaskRunnerJobStatus.Pending => "bg-yellow-500",
                            TaskRunnerJobStatus.Running => "bg-blue-500",
                            TaskRunnerJobStatus.Finished => "bg-green-500",
                            TaskRunnerJobStatus.Error => "bg-red-500",
                            _ => "bg-gray-500"
                        };
                    }
                    <span class="px-2 py-1 rounded-full text-white @bgColor">
                        @job.Status
                    </span>
                </SortableTableColumn>
                <SortableTableColumn>@(job.IsOnDemand ? "Yes" : "No")</SortableTableColumn>
                <SortableTableColumn Title="@job.ErrorMessage">
                    @if (!string.IsNullOrEmpty(job.ErrorMessage))
                    {
                        <span class="text-red-600 dark:text-red-400">@(job.ErrorMessage.Length > 50 ? job.ErrorMessage[..50] + "..." : job.ErrorMessage)</span>
                    }
                </SortableTableColumn>
            </SortableTableRow>
        }
    </SortableTable>
</div>

@code {
    private readonly List<TableColumn> _tableColumns =
    [
        new TableColumn { Title = "ID", PropertyName = "Id" },
        new TableColumn { Title = "Date", PropertyName = "RunDate" },
        new TableColumn { Title = "Start", PropertyName = "StartTime" },
        new TableColumn { Title = "End", PropertyName = "EndTime" },
        new TableColumn { Title = "Status", PropertyName = "Status" },
        new TableColumn { Title = "On-Demand", PropertyName = "IsOnDemand" },
        new TableColumn { Title = "Error", PropertyName = "ErrorMessage" },
    ];

    private List<TaskRunnerJob> JobList { get; set; } = [];
    private int CurrentPage { get; set; } = 1;
    private int PageSize { get; set; } = 5;
    private int TotalRecords { get; set; }
    private string SortColumn { get; set; } = "Id";
    private SortDirection SortDirection { get; set; } = SortDirection.Descending;

    /// <summary>
    /// Refreshes the data displayed in the table.
    /// </summary>
    public async Task RefreshData()
    {
        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        var query = dbContext.TaskRunnerJobs.AsQueryable();

        // Apply sorting
        query = SortDirection == SortDirection.Ascending
            ? query.OrderBy(x => EF.Property<object>(x, SortColumn))
            : query.OrderByDescending(x => EF.Property<object>(x, SortColumn));

        TotalRecords = await query.CountAsync();
        JobList = await query
            .Skip((CurrentPage - 1) * PageSize)
            .Take(PageSize)
            .ToListAsync();

        StateHasChanged();
    }

    /// <inheritdoc/>
    protected override async Task OnInitializedAsync()
    {
        await RefreshData();
    }

    private async Task HandlePageChanged(int newPage)
    {
        CurrentPage = newPage;
        await RefreshData();
    }

    private async Task HandleSortChanged((string column, SortDirection direction) sort)
    {
        SortColumn = sort.column;
        SortDirection = sort.direction;
        await RefreshData();
    }
}
