@page "/exercises"
@page "/{UserId}/exercises"

@inject ApiClient Api
@inject NavigationManager Navigation
@inject UserContext UserContext

<PageTitle>Exercises</PageTitle>

<div class="page">
    <header class="page-header">
        <h1>Exercises</h1>
        <p>Create and manage your exercise list.</p>
        <button class="primary" @onclick="ToggleCreate">@(ShowCreateExercise ? "Close" : "+")</button>
    </header>

    @if (ShowCreateExercise)
    {
        <section class="card">
            <h2>Add Exercise</h2>
            <div class="form-row">
                <input class="input" placeholder="Exercise name" @bind="NewExerciseName" @bind:event="oninput" />
                <button class="primary" @onclick="CreateExerciseAsync" disabled="@string.IsNullOrWhiteSpace(NewExerciseName)">Add</button>
            </div>
        </section>
    }

    <section class="card">
        <h2>Your Exercises</h2>
        @if (IsLoading)
        {
            <p>Loading...</p>
        }
        else if (ExerciseList.Count == 0)
        {
            <p class="muted">No exercises yet. Add your first one above.</p>
        }
        else
        {
            <div class="list">
                @foreach (var exercise in ExerciseList)
                {
                    <div class="list-item">
                        @if (EditingId == exercise.Id)
                        {
                            <input class="input" @bind="EditingName" @bind:event="oninput" />
                            <button class="primary" @onclick="() => SaveEditAsync(exercise.Id)">Save</button>
                            <button class="ghost" @onclick="CancelEdit">Cancel</button>
                        }
                        else
                        {
                            <div class="item-title">@exercise.Name</div>
                            <div class="actions">
                                <button class="ghost" @onclick="() => StartEdit(exercise)" aria-label="Edit exercise">✏️</button>
                                <button class="ghost" @onclick="() => DeleteExerciseAsync(exercise.Id)" aria-label="Delete exercise">🗑️</button>
                            </div>
                        }
                    </div>
                }
            </div>
        }
    </section>
</div>

@code {
    [Parameter]
    public string? UserId { get; set; }

    private List<ExerciseDto> ExerciseList { get; set; } = new();
    private bool IsLoading { get; set; } = true;
    private bool ShowCreateExercise { get; set; }
    private string NewExerciseName { get; set; } = string.Empty;
    private int? EditingId { get; set; }
    private string EditingName { get; set; } = string.Empty;

    protected override async Task OnInitializedAsync()
    {
        var ensured = await Api.EnsureUserAsync(UserId);
        if (string.IsNullOrWhiteSpace(ensured))
        {
            return;
        }

        UserContext.SetUserId(ensured);
        if (UserId != ensured)
        {
            Navigation.NavigateTo($"/{ensured}/exercises", true);
            return;
        }

        await LoadExercisesAsync();
    }

    private async Task LoadExercisesAsync()
    {
        IsLoading = true;
        ExerciseList = await Api.GetExercisesAsync(UserContext.UserId);
        IsLoading = false;
    }

    private async Task CreateExerciseAsync()
    {
        if (string.IsNullOrWhiteSpace(NewExerciseName))
        {
            return;
        }

        var result = await Api.CreateExerciseAsync(UserContext.UserId, new ExerciseUpsertRequest(NewExerciseName));
        if (result is not null)
        {
            ExerciseList.Add(result);
            ExerciseList = ExerciseList.OrderBy(e => e.Name).ToList();
            NewExerciseName = string.Empty;
        }
    }

    private void ToggleCreate()
    {
        ShowCreateExercise = !ShowCreateExercise;
    }

    private void StartEdit(ExerciseDto exercise)
    {
        EditingId = exercise.Id;
        EditingName = exercise.Name;
    }

    private void CancelEdit()
    {
        EditingId = null;
        EditingName = string.Empty;
    }

    private async Task SaveEditAsync(int exerciseId)
    {
        if (string.IsNullOrWhiteSpace(EditingName))
        {
            return;
        }

        var result = await Api.UpdateExerciseAsync(UserContext.UserId, exerciseId, new ExerciseUpsertRequest(EditingName));
        if (result is not null)
        {
            var index = ExerciseList.FindIndex(e => e.Id == exerciseId);
            if (index >= 0)
            {
                ExerciseList[index] = result;
                ExerciseList = ExerciseList.OrderBy(e => e.Name).ToList();
            }
        }

        CancelEdit();
    }

    private async Task DeleteExerciseAsync(int exerciseId)
    {
        await Api.DeleteExerciseAsync(UserContext.UserId, exerciseId);
        ExerciseList.RemoveAll(e => e.Id == exerciseId);
    }
}
