@page "/plants/list"
@page "/plants"

@using Models.BaseData
@inject IPlantsUtils PlantsUtils

<h3>Plant List</h3>
<a class="btn btn-primary mb-2" href="/plants/add">Create New Plant </a>
@if (plants == null)
{
    <p><em>Loading...</em></p>
}
else if (!plants.Any())
{
    <p>No plants available.</p>
}
else
{
    <table class="@Statics.TableClass">
        <thead>
            <tr>
                <th>Name</th>
                <th>Icon</th>
                <th>Knowledge Base</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var plant in plants)
            {
                <tr>
                    <td>@plant.Name</td>
                    <td><img src="@Statics.UploadFolder/@plant.ImageFileName" style="width:150px;" /></td>
                    <td>@plant.KnowledgeBase</td>
                    <td>
                        <button class="btn btn-primary" @onclick="() => EditPlant(plant.Id)">Edit</button>
                        <button class="btn btn-danger" @onclick="() => DeletePlant(plant.Id)">Delete</button>
                    </td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private List<PlantViewModel> plants;

    protected override async Task OnInitializedAsync()
    {
        await LoadPlants();
    }

    private async Task LoadPlants()
    {
        var response = await PlantsUtils.List();
        if (response.IsSuccessStatusCode)
        {
            plants = await response.Content.ReadFromJsonAsync<List<PlantViewModel>>();
        }
        else
        {
            plants = new List<PlantViewModel>();
        }
    }

    private void EditPlant(Guid? id)
    {
        NavigationManager.NavigateTo($"/plants/edit/{id}");
    }

    private async Task DeletePlant(Guid? id)
    {
        var confirm = await SwalUtils.ShowSwal("", "Are you sure you want to delete this plant?", SweetAlertIcon.Question);
        if (!confirm.IsConfirmed)
            return;
        var response = await PlantsUtils.Delete(id.Value);
        if (response.IsSuccessStatusCode)
        {
            await LoadPlants();
        }
    }
}
