@inherits ViewModelTemplate<OrderListViewModel>
@using Dynamicweb.Frontend
@using Dynamicweb.Rendering
@using Dynamicweb.Ecommerce.Frontend
@using Dynamicweb.Ecommerce.ProductCatalog

@{
    string baseUrl = SearchEngineFriendlyURLs.GetFriendlyUrl($"default.aspx?ID={Pageview.Page.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 justify-content-between mb-4">
    <h1 class="h4 mb-0">@(Pageview.Page.GetDisplayName())</h1>

    <button type="button" class="btn btn-sm btn-primary hstack gap-2 ms-auto py-2 px-3" data-dw-button
        hx-trigger="click"
        hx-get="@(baseUrl)"
        hx-vals='{"LayoutTemplate": "/Designs/Swift-v2/eCom/CustomerExperienceCenter/Orders/Modals/CreateCartModal.cshtml"}'
        hx-target="main"
        hx-swap="beforeend">
        <span class="icon-2 text-opacity-50">
            @ReadFile("/Files/Images/Icons/plus.svg")
        </span>
        @Translate("Add cart")
    </button>
</header>

<form hx-get="@(baseUrl)"
    hx-trigger="submit, 
                input from:input[name='FilterText'] changed delay:500ms queue:last, 
                click from:button[type='reset'], 
                change from:input[name='FilterOrderStateId'], 
                change from:input[name='SortBy']"
    hx-sync="this:abort"
    hx-swap="outerHTML"
    hx-disinherit="*"
    hx-target="[data-swift-cart-list]"
    hx-select="[data-swift-cart-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 carts")"
                    autocomplete="off"
                    maxlength="255"
                    name="FilterText" 
                    value="@Dynamicweb.Context.Current?.Request.QueryString.Get("FilterText")"
                    aria-label="@Translate("Search carts")"
                    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>
        <div class="dropdown hstack">
            <button class="btn btn-sm btn-outline-secondary hstack gap-2 ms-auto py-2 px-3 text-body" data-dw-button type="button" data-bs-toggle="dropdown" aria-expanded="false">
                <span class="icon-2">
                    @ReadFile("/Files/Images/Icons/filter.svg")
                </span>
                @Translate("Filter")
            </button>
            <div class="dropdown-menu p-3">
                <div class="fw-bold mb-1">@Translate("Status")</div>
                <div class="d-flex flex-wrap gap-2" role="group" aria-label="@Translate("Filter by status")">
                    <input class="btn-check" type="radio" name="FilterOrderStateId" value="" id="state_all" autocomplete="off" checked="@((Dynamicweb.Context.Current?.Request.QueryString.Get("FilterOrderStateId") ?? string.Empty) == string.Empty)">
                    <label for="state_all" class="fs-8 py-1 px-2 btn btn-outline-secondary text-body lh-1" data-dw-button>@Translate("All")</label>
                    @if(Model.TryGetOrderStates(out var cartStates) is true)
                    {
                        foreach (var state in cartStates)
                        {
                            var isChecked = (Dynamicweb.Context.Current?.Request.QueryString.Get("FilterOrderStateId")) == state.Id;
                            <input class="btn-check" type="radio" name="FilterOrderStateId" value="@(state.Id)" id="state_@(state.Id)" autocomplete="off" checked="@isChecked">
                            <label for="state_@(state.Id)" class="fs-8 py-1 px-2 btn btn-outline-secondary text-body lh-1" data-dw-button>@(state.Name)</label>
                        }
                    }
                </div>
            </div>
        </div>
    </nav>

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

        <div class="card overflow-hidden">
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="Id" class="visually-hidden" checked="@(currentSortBy=="Id")" />
                                    @Translate("Cart number") 
                                    @if(currentSortBy=="Id") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="CreatedAt" class="visually-hidden" checked="@(currentSortBy=="CreatedAt")" />
                                    @Translate("Created") 
                                    @if(currentSortBy=="CreatedAt") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="StateId" class="visually-hidden" checked="@(currentSortBy=="StateId")" />
                                    @Translate("Status") 
                                    @if(currentSortBy=="StateId") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>@Translate("Qty")</th>
                            <th>
                                <label class="hstack gap-1" role="button">
                                    <input type="radio" name="SortBy" value="Price" class="visually-hidden" checked="@(currentSortBy=="Price")" />
                                    @Translate("Total") 
                                    @if(currentSortBy=="Price") {
                                        <span class="icon-1">@arrow</span>
                                    }
                                </label>
                            </th>
                            <th>@Translate("Actions")</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ( var order in Model.Orders )
                        {
                            bool isActiveCart = Dynamicweb.Ecommerce.Common.Context.Cart?.Id == order.Id;

                            <tr class="position-relative" style="@(isActiveCart ? "--bs-table-bg: rgba(var(--bs-body-color-rgb), .03);" : null)">
                                <td>
                                    <div class="vstack position-relative" style="max-inline-size: min-content;">
                                        <a href="@(baseUrl)?OrderId=@(order.Id)" class="hstack gap-2 text-decoration-none text-decoration-underline-hover position-relative z-2" style="margin-top:-1.2rem;">
                                            @(order.Id)
                                            
                                            @if(isActiveCart)
                                            {
                                                <span class="hstack text-success align-self-auto" data-bs-toggle="tooltip" title="@Translate("Active cart")">
                                                    <span class="icon-2">
                                                        @ReadFile("/Files/Images/Icons/circle-check.svg")
                                                    </span>
                                                </span>
                                            }
                                        </a>
                                        <a href="@(baseUrl)?OrderId=@(order.Id)" class="fs-8 text-muted text-truncate position-absolute top-100 w-100 text-decoration-none" data-bs-toggle="tooltip" title="@(order.DisplayName)">
                                            @if(!string.IsNullOrEmpty(order.DisplayName))
                                            {
                                                @order.DisplayName
                                            } 
                                            else
                                            {
                                                <span class="text-muted">-</span>
                                            }
                                        </a>
                                    </div>
                                </td>
                                <td>
                                    <div class="vstack">
                                        @(order.CreatedAt.ToShortDateString())
                                        <span class="fs-8 text-muted">@(order.CreatedAt.ToShortTimeString())</span>
                                    </div>
                                </td>
                                <td>
                                    @if (order.TryGetOrderState(out var state))
                                    {
                                        <span class="badge lh-sm badge-neutral-light" style="@(state.StateColor is not null ? $"background-color: color-mix(in srgb, {state.StateColor?.Hex} 20%, transparent) !important; color: {state.StateColor?.Hex} !important" : null)">
                                            @Translate(state.Name)
                                        </span>
                                    }
                                </td>
                                <td>@(order.SumProductQuantities())</td>
                                <td>
                                    <div class="text-price">@(order.Price.PriceFormatted)</div>
                                </td>
                                <td>
                                    <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-2">
                                                @ReadFile("/Files/Images/Icons/ellipsis.svg")
                                            </span>
                                        </button>
                                        <ul class="dropdown-menu">
                                            <li>
                                                <a class="dropdown-item hstack gap-2" href="@(baseUrl)?OrderId=@(order.Id)">
                                                    <span class="icon-2">
                                                        @ReadFile("/Files/Images/Icons/eye.svg")
                                                    </span>
                                                    @Translate("View")
                                                </a>
                                            </li>
                                            <li>
                                                <button type="button" class="dropdown-item hstack gap-2"
                                                    hx-trigger="click"
                                                    hx-get="/dwapi/ecommerce/carts/@(order.Secret)" 
                                                    hx-headers='{"x-dw-template": "/Designs/Swift-v2/eCom/CustomerExperienceCenter/Orders/Modals/CheckoutCartModal.cshtml", "x-dw-culture": "@Pageview?.Area?.CultureInfo?.Name", "accept": "text/html"}'
                                                    hx-target="main"
                                                    hx-swap="beforeend"
                                                >
                                                    <span class="icon-2">
                                                        @ReadFile("/Files/Images/Icons/cart-shopping.svg")
                                                    </span>
                                                    @Translate("Go to checkout")
                                                </button>
                                            </li>
                                            <li>
                                                <button type="button" class="dropdown-item hstack gap-2 ps-2 pe-3 rounded-1" @(isActiveCart ? "disabled" : null) 
                                                        hx-get="@(baseUrl)"
                                                        hx-swap="outerHTML"
                                                        hx-replace-url="false"
                                                        hx-vals='{"CartID": "@order.Id", "CartCmd": "setcart"}'
                                                        hx-target="[data-swift-cart-list]"
                                                        hx-select="[data-swift-cart-list]">
                                                    <span class="icon-2">
                                                        @ReadFile("/Files/Images/Icons/circle-check.svg")
                                                    </span>
                                                    @Translate("Set as active")
                                                </button>
                                            </li>
                                            <li><hr class="dropdown-divider"></li>
                                            <li>
                                                <button type="button" class="dropdown-item hstack gap-2"
                                                    hx-trigger="click"
                                                    hx-get="/dwapi/ecommerce/carts/@(order.Secret)" 
                                                    hx-headers='{"x-dw-template": "/Designs/Swift-v2/eCom/CustomerExperienceCenter/Orders/Modals/RenameCartModal.cshtml", "x-dw-culture": "@Pageview?.Area?.CultureInfo?.Name", "accept": "text/html"}'
                                                    hx-target="main"
                                                    hx-swap="beforeend"
                                                >
                                                    <span class="icon-2">
                                                        @ReadFile("/Files/Images/Icons/pen.svg")
                                                    </span>
                                                    @Translate("Edit")
                                                </button>
                                            </li>
                                            <li>
                                                <a class="dropdown-item hstack gap-2" href="@(baseUrl)?cartcmd=copyExtended&CartId=@(order.Id)&CartUserID=@(order.CustomerUserId)&CartName=@($"Copy_of_{order.Id}")">
                                                    <span class="icon-2">
                                                        @ReadFile("/Files/Images/Icons/copy.svg")
                                                    </span>
                                                    @Translate("Copy")
                                                </a>
                                            </li>
                                            <li><hr class="dropdown-divider"></li>
                                            <li>
                                                <button type="button" class="dropdown-item hstack gap-2 text-danger"
                                                    hx-trigger="click"
                                                    hx-get="/dwapi/ecommerce/carts/@(order.Secret)" 
                                                    hx-headers='{"x-dw-template": "/Designs/Swift-v2/eCom/CustomerExperienceCenter/Orders/Modals/DeleteCartModal.cshtml", "x-dw-culture": "@Pageview?.Area?.CultureInfo?.Name", "accept": "text/html"}'
                                                    hx-target="main"
                                                    hx-swap="beforeend"
                                                >
                                                    <span class="icon-2">
                                                        @ReadFile("/Files/Images/Icons/trash.svg")
                                                    </span>
                                                    @Translate("Delete")
                                                </button>
                                            </li>
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                        }

                        @if( Model.Orders.Count() < 1 )
                        {
                            <tr class="position-relative">
                                <td class="text-center py-5" colspan="8">
                                    <div data-swift-empty-state>
                                        <div data-swift-empty-state-icon>
                                            <span class="icon">
                                                @ReadFile("/Files/Images/Icons/cart-shopping.svg")
                                            </span>
                                        </div>
                                        <div>@Translate("No carts found")</div>
                                    </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>