@page "/Accounts/Index"

@using Gremlin_BlazorServer.Data.EntityClasses;
@using Gremlin_BlazorServer.Services;

@inject AccountService accountService

<h1>Accounts</h1>

<div class="text-center bg-blue-100">
    <input class="border-4 w-1/3 rounded m-6 p-6 h-8
               border-blue-300" @bind-value="searchAccount"
    @bind-value:event="oninput" placeholder="Search by AccountName"
    @onchange="SearchAccount_OnChange"/>
</div>

<NavLink class="nav-link" href="Accounts/Add">
    <span class="oi oi-plus" aria-hidden="true">Add New Account</span>
</NavLink>


@if (allAccounts is null)
{
        <p><em>Loading... !</em></p>
}
else
{
    <p>Es wurden @filteredAccounts.Count Accounts gefunden.</p> 
    @if (allAccounts != null)
        {
            <table class="table">
                <thead>
                    <tr>
                        <th>@nameof(Account.AccountId)</th>
                        <th>@nameof(Account.AccountName)</th>
                        <th>@nameof(Account.Street)</th>
                        <th>@nameof(Account.ZIP)</th>
                        <th>@nameof(Account.City)</th>
                        <th>@nameof(Account.SAPAccountNumber)</th>
                    </tr>
                </thead>
                <tbody>
                @foreach (Account account in filteredAccounts)
                    {<tr>
                        <td>@account.AccountId</td>
                        <td>@account.AccountName</td>
                        <td>@account.Street</td>
                        <td>@account.ZIP</td>
                        <td>@account.City</td>
                        <td>@account.SAPAccountNumber</td>
                        <td>
                            <a class="nav-link" href="Accounts/Edit/@account.AccountId">
                                <span class="oi oi-pencil" aria-hidden="true">Edit</span>
                            </a>
                            <a class="nav-link" href="Accounts/Delete/@account.AccountId">
                                <span class="oi oi-trash" aria-hidden="true">Delete</span>
                            </a>
                        </td>
                    </tr>}
                </tbody>
            </table>
        }
}


@code {

    public string searchAccount = "";
    List<Account> allAccounts = new();
    List<Account> filteredAccounts = new();

    protected override async Task OnInitializedAsync()
    {
        allAccounts = await Task.Run(() => accountService.GetAllAccountsAsync());
        filteredAccounts = allAccounts;
    }

    private void SearchAccount_OnChange()
    {
        filteredAccounts = allAccounts.Where(a => a.AccountName.ToLower().Contains(searchAccount.ToLower())).ToList();
    }
}