@page "/teams/create"
@using Microsoft.EntityFrameworkCore
@inject AppDbContext Context
@inject NavigationManager NavigationManager

<PageTitle>Create Team - TSA Chapter Organizer</PageTitle>

<MudText Typo="Typo.h3">Create</MudText>
<MudText Typo="Typo.h4">Team</MudText>
<MudDivider />

<EditForm method="post" Model="Team" OnValidSubmit="AddTeam" FormName="create" Enhance>
    <DataAnnotationsValidator />
    <MudGrid>
        <MudItem xs="12" sm="7">
            <MudPaper Class="pa-4">
                <MudSelect T="EventDefinition" @bind-Value="@Team.Event" Label="Event">

                    @foreach (var evt in _events)
                    {
                        <MudSelectItem T="EventDefinition" Value="@(evt)"></MudSelectItem>
                    }
                </MudSelect>
                <MudTextField T="string?" Label="Number" @bind-Value="Team.Identifier" For="@(() => Team.Identifier)"></MudTextField>

            </MudPaper>
        </MudItem>
    </MudGrid>
    <MudButton StartIcon="@Icons.Material.Filled.ArrowBack" Href="students">Back</MudButton>
    <MudButton StartIcon="@Icons.Material.Filled.Add" OnClick="AddTeam">Add</MudButton>
</EditForm>

@code {
    [SupplyParameterFromForm]
    private Team Team { get; set; } = new();

    private List<EventDefinition>? _events;

    protected override async Task OnInitializedAsync()
    {
        _events =
            await Context.Events
                .OrderBy(e => e.Name)
                .ToListAsync();
    }

    private async Task AddTeam()
    {
        Team.Identifier = Team.Event.Name;
        Context.Teams.Add(Team);
        
        await Context.SaveChangesAsync();
        NavigationManager.NavigateTo("/teams");
    }
}