@page "/homeworks/{IdSchoolSubject:int}"
@attribute [Authorize]
@rendermode InteractiveServer
@using Microsoft.AspNetCore.Authorization
@using WorkManagementTool.Services
@using WorkManagementTool.Data.Entities
@inject HomeworkService HomeworkService

<h3>HomeworkListing</h3>

<NavLink class="btn btn-primary" href="@($"/homeworks/creation/{IdSchoolSubject}")">+</NavLink>

<div class="form-check mb-3">
    <input type="checkbox"
           class="form-check-input"
           id="showCompleted"
           @bind="showCompleted"
           @bind:after="LoadHomeworksAsync">
    <label class="form-check-label" for="showCompleted">Show Completed</label>
</div>

@if (homeworks == null)
{
    <p>Loading...</p>
}
else if (homeworks.Count == 0)
{
    <p>No homework found</p>
}
else
{
    <ul>
        @foreach (var homework in homeworks)
        {
            <li>
                <p>
                    <strong>@homework.Title</strong> - Due: @homework.DueDate.ToShortDateString() - Completed: @(homework.IsCompleted ? "Yes" : "No")
                </p>
                <div class="btn-group">
                    <HomeworkDeletion HomeworkId="@homework.Id" OnDeleted="HandleDeletion" />
                    <HomeworkToogling IdHomework="@homework.Id" OnToogle="LoadHomeworksAsync" />
                </div>
            </li>
        }
    </ul>
}

@code {
    private List<Homework>? homeworks;
    [Parameter]
    public int IdSchoolSubject { get; set; }
    private bool showCompleted { get; set; } = false;

    protected override async Task OnInitializedAsync()
    {
        await LoadHomeworksAsync();
    }

    private async Task HandleDeletion(int deletedIt)
    {
        homeworks?.RemoveAll(s => s.Id == deletedIt);
        StateHasChanged();
    }

    private async Task HandleToogle(int toogleId)
    {
        var toogledHomework = homeworks?
            .Where(w => w.Id == toogleId)
            .FirstOrDefault();
        
        toogledHomework?.IsCompleted = !toogledHomework.IsCompleted;

        StateHasChanged();
    }

    private async Task LoadHomeworksAsync()
    {
        homeworks = new();
        var uncompletedHomework = await HomeworkService.GetUncompletedHomeworkAsync(IdSchoolSubject);
        homeworks.AddRange(uncompletedHomework);

        if (showCompleted)
        {
            var completedHomework = await HomeworkService.GetCompletedHomeworksAsync(IdSchoolSubject);
            homeworks.AddRange(completedHomework);
        }
    }
}
