@page "/teams/create"
@attribute [Authorize]
@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" Value="@Team.Event" ValueChanged="OnEventChanged" Label="Event">

                    @foreach (var evt in _events)
                    {
                        <MudSelectItem T="EventDefinition" Value="@(evt)"></MudSelectItem>
                    }
                </MudSelect>
                @if (_existingTeams?.Count == 1)
                {
                    <MudAlert Severity="Severity.Info" Class="my-2">
                        A team for @Team.Event.Name already exists. This will be team 2, and the existing team will become team 1.
                    </MudAlert>
                }
                else if (_existingTeams?.Count >= 2)
                {
                    <MudAlert Severity="Severity.Error" Class="my-2">
                        Two teams for @Team.Event.Name already exist. Cannot create a third team.
                    </MudAlert>
                }

                <MudDivider Class="my-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>
    @if (!string.IsNullOrEmpty(_errorMessage))
    {
        <MudAlert Severity="Severity.Error" Class="mt-3">@_errorMessage</MudAlert>
    }
    <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;
    private List<Student> _students = [];
    private IEnumerable<Student> _selectedStudents = [];
    private string? _errorMessage;
    private List<Team>? _existingTeams;

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

        _students = await Context.Students.ToListAsync();
    }

    private async Task OnEventChanged(EventDefinition selectedEvent)
    {
        Team.Event = selectedEvent;

        // Clear any previous error messages
        _errorMessage = null;

        // Get all existing teams for this event
        _existingTeams = await Context.Teams
            .Include(t => t.Event)
            .Where(t => t.Event.Id == selectedEvent.Id)
            .ToListAsync();
    }

    private async Task AddTeam()
    {
        // Clear previous error message
        _errorMessage = null;

        // Get current count of teams for this event
        var existingTeamCount = await Context.Teams
            .CountAsync(t => t.Event.Id == Team.Event.Id);

        // Prohibit creation of third team
        if (existingTeamCount >= 2)
        {
            _errorMessage = $"Cannot create a third team for {Team.Event.Name}. Maximum of 2 teams allowed.";
            return;
        }

        // Handle automatic numbering based on event format
        if (Team.Event.EventFormat == EventFormat.Individual && _selectedStudents.Count() == 1)
        {
            // For individual events, use student's first name as identifier
            var student = _selectedStudents.First();
            Team.Identifier = student.FirstName;
            Team.Captain = student;
        }
        else if (existingTeamCount == 1)
        {
            // This is the second team - assign numbers
            var existingTeam = await Context.Teams
                .FirstOrDefaultAsync(t => t.Event.Id == Team.Event.Id);

            if (existingTeam != null)
            {
                // Update existing team to number 1
                existingTeam.Identifier = "1";
                Context.Teams.Update(existingTeam);
            }

            // Set new team to number 2
            Team.Identifier = "2";
        }
        else
        {
            // This is the first team - no number
            Team.Identifier = null;
        }

        // Add selected students to the team
        foreach (var student in _selectedStudents)
        {
            Team.Students.Add(student);
        }

        Context.Teams.Add(Team);

        await Context.SaveChangesAsync();
        NavigationManager.NavigateTo("/teams");
    }
}