@page "/homeworks/creation/{IdSchoolSubject:int}"

@using System.Threading.Tasks
@using WorkManagementTool.Services
@using WorkManagementTool.Data.Entities

@inject HomeworkService HomeworkService
@inject NavigationManager NavigationManager
@inject SchoolSubjectService SchoolSubjectService

<h3>HomeworkCreation</h3>

@if (SchoolSubject is null)
{
    <p>School subject not found</p>
}
else
{
    <EditForm Model="@Model" OnValidSubmit="Submit" FormName="homeworks-creation">
        <DataAnnotationsValidator />
        <ValidationSummary />

        <div class="form-group">
            <label for="title" class="form-label">Title</label>
            <InputText id="title" class="form-control" @bind-Value="Model!.Title" />
        </div>
        <div class="form-group">
            <label for="description" class="form-label">Description</label>
            <InputTextArea id="description" class="form-control" @bind-Value="Model!.Description" />
        </div>
        <div class="form-group">
            <label for="dueDate" class="form-label">Due date</label>
            <InputDate id="dueDate" class="form-control" @bind-Value="Model!.DueDate" />
        </div>
        <div class="form-group form-check">
            <InputCheckbox id="isCompleted" class="form-check-input" @bind-Value="Model!.IsCompleted" />
            <label for="isCompleted" class="form-check-label">Completed</label>
        </div>
        <div class="form-group">
            <label for="deliveryMethod" class="form-label">Delivery method</label>
            <InputText id="deliveryMethod" class="form-control" @bind-Value="Model!.DeliveryMethod" />
        </div>
        <button type="submit" class="btn btn-primary">+</button>
    </EditForm>
}

@code {
    [SupplyParameterFromForm]
    private Homework? Model { get; set; }

    [Parameter]
    public int IdSchoolSubject { get; set; }

    private SchoolSubject? SchoolSubject { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Model ??= new Homework
        {
            Title = null!,
            Deleted = false,
            DueDate = DateTime.Now.AddDays(1),
            IsCompleted = false,
        };
        SchoolSubject = await SchoolSubjectService.GetSchoolSubjectByIdAsync(IdSchoolSubject);
    }

    private async Task Submit()
    {
        if (Model is not null && SchoolSubject is not null)
        {
            Model!.SchoolSubject = SchoolSubject!;
            await HomeworkService.AddHomeworkAsync(Model!);
            NavigationManager.NavigateTo($"/homeworks/{IdSchoolSubject}");
        }
    }
}
