@page "/Contacts/Index"

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

@inject ContactService contactService

<h1>Contacts</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="searchContact"
    @bind-value:event="oninput" placeholder="Search by LastName"
    @onchange="SearchContact_OnChange"/>
</div>

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


@if (allContacts is null)
{
        <p><em>Loading... !</em></p>
}
else
{
    <p>Es wurden @filteredContacts.Count Contacts gefunden.</p> 
    @if (allContacts != null)
        {
            <table class="table">
                <thead>
                    <tr>
                        <th>@nameof(Contact.ContactId)</th>
                        <th>@nameof(Contact.AccountId)</th>
                        <th>@nameof(Contact.LastName)</th>
                        <th>@nameof(Contact.FirstName)</th>
                        <th>@nameof(Contact.Gender)</th>
                        <th>@nameof(Contact.EMail)</th>
                        <th>@nameof(Contact.SAPContactNumber)</th>
                    </tr>
                </thead>
                <tbody>
                @foreach (Contact Contact in filteredContacts)
                    {<tr>
                        <td>@Contact.ContactId</td>
                        <td>@Contact.AccountId</td>
                        <td>@Contact.LastName</td>
                        <td>@Contact.FirstName</td>
                        <td>@Contact.Gender</td>
                        <td>@Contact.EMail</td>
                        <td>@Contact.SAPContactNumber</td>
                        <td>
                            <a class="nav-link" href="Contacts/Edit/@Contact.ContactId">
                                <span class="oi oi-pencil" aria-hidden="true">Edit</span>
                            </a>
                            <a class="nav-link" href="Contacts/Delete/@Contact.ContactId">
                                <span class="oi oi-trash" aria-hidden="true">Delete</span>
                            </a>
                        </td>
                    </tr>}
                </tbody>
            </table>
        }
}

@code {

    public string searchContact = "";
    List<Contact> allContacts = new();
    List<Contact> filteredContacts = new();

    protected override async Task OnInitializedAsync()
    {
        allContacts = await Task.Run(() => contactService.GetAllContactsAsync());
        filteredContacts = allContacts;
    }

    private void SearchContact_OnChange()
    {
        filteredContacts = allContacts.Where(a => a.LastName.ToLower().Contains(searchContact.ToLower())).ToList();
    }
}