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

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

<MudText Typo="Typo.h3">Edit</MudText>
<MudText Typo="Typo.h4">Team @(Team.ToString())</MudText>

@if (Team is null)
{
    <p><em>Loading...</em></p>
}
else
{
    <EditForm method="post" Model="Team" OnValidSubmit="UpdateTeam" FormName="edit" Enhance>
        <DataAnnotationsValidator/>
        <MudGrid>
            <MudItem xs="12" sm="7">
                <MudPaper Class="pa-4">
                    <MudSelect 
                        T="Student"
                        MultiSelection="true" 
                        @bind-SelectedValues="@_selectedStudents"
                        ToStringFunc="e => e.Name"
                        Label="Students">

                        @foreach (var student in _students.OrderBy(e => e.FirstName))
                        {
                            <MudSelectItem T="Student" Value="@student">@student.Name</MudSelectItem>
                        }
                    </MudSelect>
                    <MudStack>
                        <MudText>Captain</MudText>
                        <MudToggleGroup T="Student" SelectionMode="SelectionMode.ToggleSelection" @bind-Value="Team.Captain" CheckMark>
                            @foreach (var student in _selectedStudents.OrderBy(e => e.FirstName))
                            {
                                <MudToggleItem Value="@(student)" Text="@student.Name" />
                            }
                        </MudToggleGroup>
                    </MudStack>
                    <MudTextField T="string?" Label="Identifier" @bind-Value="Team.Identifier" For="@(() => Team.Identifier)" Required="false" Clearable="true"></MudTextField>
                </MudPaper>
            </MudItem>
        </MudGrid>
        <MudButton StartIcon="@Icons.Material.Filled.ArrowBack" Href="teams">Back</MudButton>
        <MudButton StartIcon="@Icons.Material.Filled.Save" OnClick="UpdateTeam">Save</MudButton>
    </EditForm>
}

@code {
    [SupplyParameterFromQuery]
    private int Id { get; set; }

    [SupplyParameterFromForm]
    private Team? Team { get; set; }

    private IEnumerable<Student> _selectedStudents = new HashSet<Student>();
    private List<Student> _students = [];

    protected override async Task OnInitializedAsync()
    {
        Team ??= await Context.Teams
            .Include(e => e.Event)
            .Include(e => e.Students)
            .FirstOrDefaultAsync(m => m.Id == Id);
        _students = await Context.Students.ToListAsync();
        foreach (var s in Team.Students)
        {
            ((HashSet<Student>)_selectedStudents).Add(s);
        }

        if (Team is null)
        {
            NavigationManager.NavigateTo("notfound");
        }

        switch (Team!.Event.EventFormat)
        {
            case EventFormat.Individual when Team.Students.Count == 1:
                Team.Captain ??= Team.Students[0];
                Team.Identifier ??= Team.Captain.FirstName;
                break;
        }
    }

    // To protect from overposting attacks, enable the specific properties you want to bind to.
    // For more information, see https://learn.microsoft.com/aspnet/core/blazor/forms/#mitigate-overposting-attacks.
    private async Task UpdateTeam()
    { 
        //Context.Attach(Team!).Entity = EntityState.Modified;
        Team.Students.Clear();
        foreach (var s in _selectedStudents)
        {
            Team.Students.Add(s);
        }

        try
        {
            await Context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!TeamExists(Team!.Id))
            {
                NavigationManager.NavigateTo("notfound");
            }
            else
            {
                throw;
            }
        }

        NavigationManager.NavigateTo("/teams");
    }

    private bool TeamExists(int id)
    {
        return Context.Teams.Any(e => e.Id == id);
    }
}
