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

@{
    string baseUrl = SearchEngineFriendlyURLs.GetFriendlyUrl($"default.aspx?ID={Pageview?.Page?.ID ?? 0}");
    string baseUrlRaw = Dynamicweb.Context.Current?.Request.RawUrl ?? string.Empty;
    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");
}

<nav aria-label="breadcrumb">
	<ol class="breadcrumb mb-3" style="--bs-breadcrumb-divider: '>'; --bs-breadcrumb-item-padding-x: 1rem; --bs-breadcrumb-font-size: .875em;">
		<li class="breadcrumb-item"><a href="@(baseUrl)">@(Pageview?.Page?.GetDisplayName())</a></li>
		<li class="breadcrumb-item active" aria-current="page">@(Model.GetCurrentGroupName())</li>
	</ol>
</nav>

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

    <div class="ms-auto">
        <a href="@(baseUrlRaw)&UserGroupCmd=inviteuser" class="btn btn-sm btn-primary hstack py-2 px-3" data-dw-button>
            <span class="icon-2 me-2">
                @ReadFile("/Files/Images/Icons/plus.svg")
            </span>
            @Translate("Invite user")
        </a>
    </div>
</header>

<form hx-get="@(baseUrlRaw)"
    hx-disinherit="*"
    hx-trigger="submit, 
        input from:input[name='FilterText'] changed delay:500ms queue:last, 
        click from:button[type='reset'],
        change from:input[name='SortBy']"
    hx-sync="this:abort"
    hx-swap="outerHTML"
    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: '' }">
                <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 id="searchField_@(Pageview?.ID)"
                    class="form-control rounded z-1 ps-5"
                    type="search"
                    placeholder="@Translate("Search users by name, number or email")..."
                    autocomplete="off"
                    maxlength="255"
                    name="FilterText"
                    value="@Dynamicweb.Context.Current?.Request.QueryString.Get("FilterText")"
                    aria-label="@Translate("Search users by name, number or email")..."
                    x-ref="searchInput"
                    x-model="searchQuery"
                >
                <button x-show="searchQuery.length > 0" 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")" @@click="searchQuery = ''; $refs.searchInput.focus();">
                    <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>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="CustomerNumber" class="visually-hidden" checked="@(currentSortBy=="CustomerNumber")" />
                                    @Translate("Customer number") 
                                    @if(currentSortBy=="CustomerNumber") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="Email" class="visually-hidden" checked="@(currentSortBy=="Email")" />
                                    @Translate("Email") 
                                    @if(currentSortBy=="Email") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>@Translate("Status")</th>
                            <th>@Translate("Invite date")</th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="LastActive" class="visually-hidden" checked="@(currentSortBy=="LastActive")" />
                                    @Translate("Last active") 
                                    @if(currentSortBy=="LastActive") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>@Translate("Actions")</th>
                        </tr>
                    </thead>

                    <tbody>
                        @foreach (var user in Model?.Users ?? [])
                        {
                            var userState = user.GetStatus();
                            var userManagementUser = Dynamicweb.Security.UserManagement.UserManagementServices.Users.GetUserById(user.ID);
                            <tr>
                                <td>
                                    <div class="hstack gap-2">
                                        @if(user.TryGetImageFile(out var 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 justify-content-center">
                                            <div class="text-wrap-nowrap">@(user.Name)</div>
                                            @if (!string.IsNullOrEmpty(user.Company)) {
                                                <div class="fs-8 text-muted">@(user.Company)</div>
                                            }
                                        </div>
                                    </div>
                                </td>
                                <td>@(user.CustomerNumber)</td>
                                <td class="text-muted text-truncate" style="max-width: 250px;">@(user.Email)</td>
                                <td>
                                    @if (userState == UserStatusType.Active) {
                                        <div class="badge lh-sm badge-neutral-dark">@Translate("Active")</div>
                                    }
                                    else if (userState == UserStatusType.Pending) 
                                    {
                                        <div class="badge lh-sm badge-neutral-light">@Translate("Pending")</div>
                                    }
                                    else if (userState == UserStatusType.Inactive || userState == UserStatusType.None) 
                                    {
                                        <div class="badge lh-sm badge-neutral">@Translate("Inactive")</div>
                                    }
                                </td>
                                <td>
                                    <div class="vstack">
                                        @(userManagementUser?.InvitationSent?.ToShortDateString() ?? "-")
                                        <span class="fs-8 text-muted">@(userManagementUser?.InvitationSent?.ToShortTimeString())</span>
                                    </div>
                                </td>
                                <td>
                                    <div class="vstack">
                                        @(userManagementUser?.LastLogOnOn?.ToShortDateString())
                                        <span class="fs-8 text-muted">@(userManagementUser?.LastLogOnOn?.ToShortTimeString())</span>
                                    </div>
                                </td>
                                <td>
                                    @if ((Pageview?.User?.ID != user.ID) && (UserContext.Current.ImpersonatingUser?.ID != user.ID)) // You cannot impersonate or delete yourself
                                    {
                                        bool canImpersonateThisUser = UserContext.Current.GetImpersonatableUsers()?.Any(u => u.ID == user.ID) == true;

                                        <div class="hstack gap-3">
                                            <button class="btn btn-icon position-relative z-2" data-dw-button type="button" data-bs-toggle="dropdown" aria-expanded="false" data-bs-popper-config='{"strategy":"fixed", "placement":"bottom-end"}'>
                                                <span class="icon">
                                                    @ReadFile("/Files/Images/Icons/ellipsis.svg")
                                                </span>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-shadow">
                                                <li>

                                                    @if (Pageview?.User?.ID != user.ID)
                                                    {
                                                        <a href="@($"{baseUrl}?NowImpersonating=true&DWExtranetSecondaryUserSelector={user.ID}&Redirect={Model?.RedirectAfterImpersonation}")"
                                                            class="dropdown-item hstack gap-2 @(!canImpersonateThisUser ? "disabled" : null)"
                                                            tabindex="@(canImpersonateThisUser ? "0" : "-1")">
                                                            <span class="icon">
                                                                @ReadFile("/Files/Images/Icons/user-group.svg")
                                                            </span>
                                                            @Translate("Impersonate")
                                                        </a>
                                                    }
                                                    else
                                                    {
                                                        <a href="@(baseUrl)?DwExtranetRemoveSecondaryUser=1"
                                                            class="dropdown-item hstack gap-2">
                                                            <span class="icon">@ReadFile("/Files/Images/Icons/arrows-repeat.svg")</span>
                                                            @Translate("Switch back to") @(UserContext.Current.ImpersonatingUser?.Name)
                                                        </a>
                                                    }
                                                </li>
                                                <li>
                                                    <button class="dropdown-item hstack gap-2"
                                                        hx-disinherit="*"
                                                        hx-post="@(baseUrlRaw)&UserGroupCmd=ChangeActiveStatus&Secret=@(user.UniqueId)"    
                                                        hx-target="[data-swift-user-list]"
                                                        hx-select="[data-swift-user-list]"
                                                        hx-swap="outerHTML"
                                                        hx-push-url="false"
                                                    >
                                                        <span class="icon">
                                                            @ReadFile("/Files/Images/Icons/user-group.svg")
                                                        </span>
                                                        @Translate(userState == UserStatusType.Active ? "Deactivate user" : "Activate user")
                                                    </button>
                                                </li>
                                                <li>
                                                    <button class="dropdown-item hstack gap-2"
                                                        hx-disinherit="*"
                                                        hx-post="@(baseUrlRaw)&UserGroupCmd=ResendInvitation&Secret=@(user.UniqueId)"
                                                        hx-target="[data-swift-user-list]"
                                                        hx-select="[data-swift-user-list]"
                                                        hx-swap="outerHTML"
                                                        hx-push-url="false"
                                                        disabled="@(userState != UserStatusType.Pending)"
                                                    >
                                                        <span class="icon">
                                                            @ReadFile("/Files/Images/Icons/envelope.svg")
                                                        </span>
                                                        @Translate("Resend invitation")
                                                    </button>
                                                </li>
                                                <li>
                                                    <button class="dropdown-item text-danger hstack gap-2"
                                                        hx-disinherit="*"
                                                        hx-post="@(baseUrlRaw)&UserGroupCmd=DeleteUser&Secret=@(user.UniqueId)"
                                                        hx-target="[data-swift-user-list]"
                                                        hx-select="[data-swift-user-list]"
                                                        hx-swap="outerHTML"
                                                        hx-push-url="false"
                                                        hx-confirm="@Translate("Are you sure you want to delete this user?")"
                                                    >
                                                        <span class="icon">
                                                            @ReadFile("/Files/Images/Icons/trash-can.svg")
                                                        </span>
                                                        @Translate("Delete")
                                                    </button>
                                                </li>
                                            </ul>
                                        </div>
                                    }
                                    else
                                    {
                                        <span>-</span> // You cannot impersonate or delete yourself
                                    }
                                </td>
                            </tr>
                        }

                        @if (Model?.Users.Count() < 1)
                        {
                            <tr>
                                <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-group.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>
        }
        

        @{
            var result = Model?.ResultType;
            var toast = result != UserGroupResultType.None ? new {
                Text = result == UserGroupResultType.UserActiveStateChanged ? Translate("The user status has been changed") : 
                result == UserGroupResultType.InvitationResent ? Translate("An invitation has been resent") : 
                result == UserGroupResultType.UserDeleted ? Translate("The user has been deleted") : 
                result == UserGroupResultType.UserInviteSuccess ? Translate("The user has been invited") :
                null,
            } : null;
            
            @if (toast is not null) 
            { 
                <div aria-live="polite" aria-atomic="true" class="position-fixed bottom-0 end-0 p-4 z-3">
                    <div class="toast toast-animate-in bg-body" role="status" aria-live="polite" aria-atomic="true" x-data x-init="const toast = new bootstrap.Toast($el, {autohide: true, delay: 5000 }); toast.show();" data-dw-colorscheme="light">
                        <div class="toast-header border-0">
                            <strong class="me-auto hstack gap-2">
                                <div class="icon-2 rounded-circle bg-success-subtle text-success-emphasis">
                                    @ReadFile("/Files/Images/Icons/circle-check.svg")
                                </div>
                                <span class="fw-bold">@Translate("Success")</span>
                            </strong>
                            <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close" style="background-size: .5rem;"></button>
                        </div>
                        <div class="toast-body pt-2 text-muted lh-sm fs-7">
                            @toast.Text
                        </div>
                    </div>
                </div>
            }
        }
    </div>

</form>