@inherits ViewModelTemplate<UserViewListViewModel>
@using Dynamicweb.Frontend
@using Dynamicweb.Rendering
@using Dynamicweb.Users.Frontend
@using Dynamicweb.Users.Frontend.UserView
@using Dynamicweb.Security.UserManagement

@{
    string baseUrl = SearchEngineFriendlyURLs.GetFriendlyUrl($"default.aspx?ID={Pageview.ID}");
    string currentSortBy = Dynamicweb.Context.Current?.Request.QueryString.Get("SortBy") ?? Pageview.CurrentParagraph?.ModuleProperties?.GetValue("SortByField") ?? string.Empty;
    string currentSortOrder = Dynamicweb.Context.Current?.Request.QueryString.Get("SortOrder") ?? Pageview.CurrentParagraph?.ModuleProperties?.GetValue("SortOrder") ?? string.Empty;
    string nextSortOrder = currentSortOrder == "asc" ? "desc" : "asc";
    string arrow = currentSortOrder == "asc" ? @ReadFile("/Files/Images/Icons/arrow-up.svg") : @ReadFile("/Files/Images/Icons/arrow-down.svg");
}

<header class="hstack gap-3 mb-4">
    <h1 class="h4 mb-0">@(Pageview.Page.GetDisplayName())</h1>
</header>

<form hx-get="@(baseUrl)"
    hx-trigger="submit, 
                input from:input[name='search'] changed delay:500ms queue:last, 
                click from:button[type='reset'], 
                change from:input[name='SortBy']" 
    hx-sync="this:abort"
    hx-swap="outerHTML"
    hx-disinherit="*"
    hx-target="[data-swift-user-list]"
    hx-select="[data-swift-user-list]"
    hx-replace-url="true"
    hx-on:click="const sortInput = event.target.closest('label')?.querySelector('input[name=SortBy]');
                 if (!sortInput) return;
                 const sortOrderField = this.querySelector('[name=SortOrder]');
                 if (!sortOrderField) return;
                 if (sortInput.checked) {
                     sortOrderField.value = sortOrderField.value === 'asc' ? 'desc' : 'asc';
                     this.requestSubmit();
                 } else {
                     sortOrderField.value = 'asc';
                 }">

    <nav class="hstack gap-2 mb-3">
        <div class="flex-fill">
            <div class="input-group" x-data="{ searchQuery: '' }" x-init="searchQuery = $refs.searchInput.value">
                <span class="input-group-text px-3 border-0 bg-transparent position-absolute top-0 bottom-0 start-0 z-2">
                    <span class="htmx-indicator spinner-border spinner-border-sm" aria-hidden="true"></span>
                    <span class="icon-2" data-swift-indicator-origin>@ReadFile("/Files/Images/Icons/magnifying-glass.svg")</span>
                </span>
                <input class="form-control rounded z-1 ps-5"
                    type="search"
                    placeholder="@Translate("Search users by name or email")"
                    autocomplete="off"
                    maxlength="255"
                    name="search" 
                    value="@Dynamicweb.Context.Current?.Request.QueryString.Get("search")"
                    aria-label="@Translate("Search users by name or email")"
                    x-ref="searchInput"
                    x-model="searchQuery"
                >
                <button x-show="searchQuery.length > 0" @@click.prevent="searchQuery = ''" type="reset" class="btn btn-link btn-sm px-3 position-absolute top-0 bottom-0 end-0 z-2" aria-label="@Translate("Clear search")">
                    <span>@Translate("Clear")</span>
                </button>
            </div>
        </div>
    </nav>

    <div data-swift-user-list>
        <input type="hidden" name="SortOrder" value="@(currentSortOrder)">

        <div class="card overflow-hidden">
            <div class="table-responsive">
                <table class="table table-md table-hover mb-0 align-middle fs-7" style="--bs-table-color: var(--bs-body-color);">
                    <thead style="--bs-table-bg: rgba(var(--bs-body-color-rgb), .0275); --bs-table-color: rgba(var(--bs-body-color-rgb), 0.5);">
                        <tr>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="Name" class="visually-hidden" checked="@(currentSortBy=="Name")" />
                                    @Translate("User") 
                                    @if(currentSortBy=="Name") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>@Translate("Customer number")</th>
                            <th>@Translate("Email")</th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="Name" class="visually-hidden" checked="@(currentSortBy=="LastLogOnOn")" />
                                    @Translate("Last active") 
                                    @if(currentSortBy=="LastLogOnOn") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>@Translate("Actions")</th>
                        </tr>
                    </thead>

                    <tbody class="border-top-0">
                        @foreach (var user in Model.Users)
                        {
                            <tr class="position-relative">
                                <td>
                                    <div class="hstack gap-2">
                                        @if(user.TryGetImageFile(out ImageFileViewModel? image))
                                        {
                                            <div class="align-self-auto hstack justify-content-center p-0" style="height:2rem; aspect-ratio:1;">
                                                <img src="@image.ToGetImage(new(){ Width = 40, Ratio = "1/1" })" alt="@user.Name" class="img-thumbnail rounded-circle" itemprop="image"/>
                                            </div>
                                        }
                                        else 
                                        {
                                            <div class="btn btn-primary rounded-circle align-self-auto hstack justify-content-center p-0 pe-none" style="height:2rem; aspect-ratio:1;" data-dw-button>
                                                <div class="d-flex dw-h6 fs-7 lh-1 m-0">
                                                    @(user.GetTwoLetterInitials())
                                                </div>
                                            </div>
                                        }
                                        <div class="vstack">
                                            <div class="text-wrap-nowrap">@(user.Name)</div>
                                            <span class="fs-8 text-muted">@(user.Company)</span>
                                        </div>
                                    </div>
                                </td>
                                <td><span>@user.CustomerNumber</span></td>
                                <td><span class="text-muted">@user.Email</span></td>
                                <td>
                                    <div class="vstack">
                                        @(Dynamicweb.Security.UserManagement.UserManagementServices.Users.GetUserById(user.ID)?.LastLogOnOn?.ToShortDateString())
                                        <span class="fs-8 text-muted">@(Dynamicweb.Security.UserManagement.UserManagementServices.Users.GetUserById(user.ID)?.LastLogOnOn?.ToShortTimeString())</span>
                                    </div>
                                </td>
                                <td>
                                    <div class="hstack gap-3">
                                        @if (Pageview.User?.ID != user.ID)
                                        {
                                            <a href="@(baseUrl)?NowImpersonating=true&DWExtranetSecondaryUserSelector=@(user.ID)&Redirect=@(Model.RedirectAfterImpersonation)"class="btn btn-outline-secondary text-body hstack border-0 p-2 position-relative z-2 me-3" data-dw-button
                                                data-bs-toggle="tooltip" data-bs-placement="top"
                                                data-bs-title="@Translate("Impersonate")"
                                                title="@Translate("Impersonate")">
                                                <span class="icon-2">
                                                    @ReadFile("/Files/Images/Icons/user-group.svg") 
                                                </span>
                                            </a>
                                        }
                                        else
                                        {
                                            <a href="@(baseUrl)?DwExtranetRemoveSecondaryUser=1"class="btn btn-secondary text-body hstack border-0 p-2 position-relative z-2 me-3" data-dw-button
                                                data-bs-toggle="tooltip" data-bs-placement="top"
                                                data-bs-title="@Translate("Switch back to") @(UserContext.Current.ImpersonatingUser?.Name)"
                                                title="@Translate("Stop impersonation")">
                                                <span class="icon-2">@ReadFile("/Files/Images/Icons/arrows-repeat.svg")</span>
                                            </a>
                                        }
                                    </div>
                                </td>
                            </tr>                    
                        }

                        @if( Model.Users.Count() < 1 )
                        {
                            <tr class="position-relative">
                                <td colspan="7">
                                    <div class="d-grid py-4">
                                        <span class="m-auto">
                                            <div class="d-grid rounded-circle m-auto" style="width:4rem;aspect-ratio:1;background-color:rgba(var(--bs-body-color-rgb), .0275);">
                                                <span class="icon-4 text-muted">
                                                    @ReadFile("/Files/Images/Icons/user.svg")
                                                </span>
                                            </div>
                                            <div class="mt-3">@Translate("No users found")</div>
                                        </span>
                                    </div>
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>

        @if (Model.PageCount > 1)
        {
            <div class="hstack justify-content-between mt-3">
                <div class="text-muted fs-7">
                    @Translate("Showing page") @(Model.CurrentPage) @Translate("of") @(Model.PageCount)
                </div>

                <div class="hstack gap-2">
                    <button type="submit" class="btn btn-outline-secondary text-body hstack p-2" name="PageNum" value="@(Model.CurrentPage - 1)" data-dw-button disabled="@(Model.CurrentPage == 1)">
                        <span class="icon-2">
                            @ReadFile("/Files/Images/Icons/chevron-left.svg")
                        </span>
                    </button>
                    <button type="submit" class="btn btn-outline-secondary text-body hstack p-2" name="PageNum" value="@(Model.CurrentPage + 1)" data-dw-button disabled="@(Model.CurrentPage == Model.PageCount)">
                        <span class="icon-2">
                            @ReadFile("/Files/Images/Icons/chevron-right.svg")
                        </span>
                    </button>
                </div>
            </div>
        }
    </div>
</form>