@page "/teams/edit"
@attribute [Authorize]
@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">
                    <StudentToggleSelector Students="@_students"
                                          @bind-SelectedStudents="_selectedStudents"
                                          Title="Students"
                                          ShowFullName="true" />
                    <MudStack Class="mt-4">
                        <TeamCaptainSelector Students="@_selectedStudents"
                                            @bind-SelectedCaptain="Team.Captain"
                                            Title="Captain" />
                    </MudStack>
                </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 = [];
    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();
        _selectedStudents = Team.Students.ToList();

        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);
        }

        // Update identifier for individual events
        if (Team.Event.EventFormat == EventFormat.Individual && Team.Students.Count == 1)
        {
            Team.Captain ??= Team.Students[0];
            Team.Identifier = Team.Captain.FirstName;
        }

        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);
    }
}
