@inherits ViewModelTemplate<FavoriteListListViewModel>
@using Dynamicweb.Rendering
@using Dynamicweb.Ecommerce.Frontend
@using Dynamicweb

@{
    int userId = Pageview?.User?.ID != null ? Pageview.User.ID : 0;

    string currentPageUrl = "/Default.aspx?ID=" + Pageview.Page.ID;
    int listsCount = Model.TotalFavoriteListsCount;
    int pageSize = Model.PageSize;
}

@if (Pageview?.User?.ID != null)
{
    <header class="hstack gap-3 justify-content-between mb-4">
        <h1 class="h4 mb-0">@(Pageview.Page.GetDisplayName())</h1>

        @if (Model.FavoriteLists != null)
        {
            if (Model.FavoriteLists.Count > 0)
            {
                <button type="button" class="btn btn-sm btn-primary hstack gap-2 ms-auto py-2 px-3" data-dw-button data-bs-toggle="modal" data-bs-target="#createFavoriteListModal" id="AddNewFavoriteList">
                    <span class="icon-2 text-opacity-50">
                        @ReadFile("/Files/Images/Icons/plus.svg")
                    </span>
                    @Translate("Add favorite list")
                </button>
            }
        }
    </header>

    <div class="h-100 border-top">
        @if (Model.FavoriteLists == null || Model.FavoriteLists.Count < 1)
        {
            <div class="grid">
                <div class="g-col-12 g-start-lg-3 g-col-lg-8 d-flex flex-column gap-3 text-center py-3">
                    <h2 class="h5 m-0">@Translate("It looks like you do not have any favorites yet")</h2>
                    <p class="m-0">@Translate("Save and arrange the best things here until you are ready for them")</p>

                    <div class="d-flex flex-column flex-sm-row gap-3 justify-content-center">
                        <button type="button" class="btn btn-primary" data-dw-button="primary" data-bs-toggle="modal" data-bs-target="#createFavoriteListModal" id="CreateNewFavoriteList">@Translate("Create favorite list")</button>
                    </div>
                </div>
            </div>
        }
        else
        {
            foreach (var theList in Model.FavoriteLists)
            {
                int listItemsCount = theList.ProductList.Products.Count;
                string productCountLabel = listItemsCount > 1 ? Translate("products") : Translate("product");
                string favoriteListLink = currentPageUrl + "&amp;FavoriteListId=" + theList.Id;
                string listName = !string.IsNullOrEmpty(theList.Name) ? theList.Name : Translate("Favorites");

                <article class="d-flex flex-column gap-3 px-2 py-3 border-bottom">

                    <header class="d-flex flex-row align-items-baseline lh-1">
                        <h3 class="flex-fill h6 m-0">
                            <a href="@favoriteListLink" class="text-decoration-none opacity-75">@Dynamicweb.Core.Encoders.HtmlEncoder.HtmlEncode(listName)</a>
                        </h3>
                        <span class="small text-end">@listItemsCount @productCountLabel <span class="d-none d-sm-inline">@Translate("in this list")</span></span>
                    </header>

                    <div class="d-md-none grid grid-2">
                        @if (listItemsCount > 0)
                        {
                            foreach (var item in theList.ProductList.Products.Take(2))
                            {
                                string productImage = "/Admin/Public/GetImage.ashx?Image=" + item.DefaultImage.Value + "&Format=webp&Width=350&Height=350";
                                productImage = !item.DefaultImage.Value.StartsWith("/Files/", StringComparison.OrdinalIgnoreCase) ? item.DefaultImage.Value : productImage;

                                <div class="ratio ratio-1x1">
                                    <a href="@favoriteListLink" class="d-flex justify-content-center align-items-center">
                                        <img src="@productImage"
                                             loading="lazy"
                                             decoding="async"
                                             class="mw-100 mh-100"
                                             alt="@item.Name">
                                    </a>
                                </div>
                            }
                        }
                        else
                        {
                            <div class="g-col-12 py-5 text-center border">
                                @Translate("This list is empty")
                            </div>
                        }
                    </div>

                    <div class="d-none d-md-grid d-print-grid grid grid-2 grid-md-5">
                        @if (listItemsCount > 0)
                        {
                            foreach (var item in theList.ProductList.Products.Take(5))
                            {
                                string productImage = "/Admin/Public/GetImage.ashx?Image=" + item.DefaultImage.Value + "&Format=webp&Width=350&Height=350";
                                productImage = !item.DefaultImage.Value.StartsWith("/Files/", StringComparison.OrdinalIgnoreCase) ? item.DefaultImage.Value : productImage;

                                <div class="ratio ratio-1x1">
                                    <a href="@favoriteListLink" class="d-flex justify-content-center align-items-center">
                                        <img src="@productImage"
                                             loading="lazy"
                                             decoding="async"
                                             class="mw-100 mh-100"
                                             alt="@item.Name">
                                    </a>
                                </div>
                            }
                        }
                        else
                        {
                            <div class="g-col-12 py-6 text-center border">
                                @Translate("This list is empty")
                            </div>
                        }
                    </div>

                    <footer class="d-flex flex-row gap-3 align-items-center justify-content-end">
                        <button type="button"
                                class="btn btn-link p-0 renameFavoriteListModal"
                                id="RenameFavoriteList"
                                data-bs-toggle="modal"
                                data-bs-target="#renameFavoriteListModal"
                                data-list-id="@theList.Id"
                                data-list-name="@Dynamicweb.Core.Encoders.HtmlEncoder.HtmlEncode(listName)">
                            @Translate("Edit")
                        </button>
                        <button type="button"
                                class="btn btn-link p-0 deleteFavoriteNameButton"
                                id="DeleteFavoriteList"
                                data-bs-toggle="modal"
                                data-bs-target="#deleteFavoriteListModal"
                                data-list-id="@theList.Id"
                                data-list-name="@Dynamicweb.Core.Encoders.HtmlEncoder.HtmlEncode(listName)">
                            @Translate("Delete")
                        </button>
                    </footer>
                </article>
            }
        }

        @if (listsCount > pageSize)
        {
            string pageHrefTemplate = string.Format("<a class=\"page-link\" href=\"{0}&PageNum={{0}}&PageSize={{1}}\">{{0}}</a>", currentPageUrl);

            <div class="p-3">
                <ul class="pagination m-0">
                    @for (int i = 1; i <= Model.PageCount; i++)
                    {
                        var css = i == Model.CurrentPage
                        ? "page-item active"
                        : "page-item";
                        <li class="@css">
                            @string.Format(pageHrefTemplate, i, Model.PageSize)
                        </li>
                    }
                </ul>
            </div>
        }
    </div>
}
else if (Pageview.IsVisualEditorMode)
{
    <div class="alert alert-dark" role="alert">
        @Translate("To work on this page, you must be signed in, in the frontend")
    </div>
}

<div class="modal fade" tabindex="-1" id="createFavoriteListModal">
    <div class="modal-dialog pt-8">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">@Translate("Create favorite list")</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p class="text-muted">@Translate("Enter a name for the list")</p>
                <div class="form-floating">
                    <input type="text" class="form-control" name="createFavoriteListInputName" id="createFavoriteListInputName" placeholder="@Translate("List name")" value=""/>
                    <label for="createFavoriteListInputName">@Translate("List name")</label>
                </div>
                <div class="alert alert-danger m-0 d-none" role="alert" id="createFavoriteListError">@Translate("A Favorite List must have a name")</div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dw-button="secondary" data-bs-dismiss="modal">@Translate("Cancel")</button>
                <button type="button" class="btn btn-primary" data-dw-button="primary" id="createFavoriteListButton">@Translate("Create list")</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" tabindex="-1" id="renameFavoriteListModal">
    <div class="modal-dialog pt-8">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">@Translate("Edit list")</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p class="text-muted">@Translate("Enter a new name for the list or change the existing name")</p>
                <div class="form-floating">
                    <input type="text" class="form-control" name="renameFavoriteListInputName" id="renameFavoriteListInputName" placeholder="@Translate("List name")" value=""/>
                    <label for="renameFavoriteListInputName">@Translate("List name")</label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dw-button="secondary" data-bs-dismiss="modal">@Translate("Cancel")</button>
                <button type="button" class="btn btn-primary" data-dw-button="primary" id="renameFavoriteListButton">@Translate("Update list")</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" tabindex="-1" id="deleteFavoriteListModal">
    <div class="modal-dialog pt-8">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">@Translate("Delete favorite list")</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body"> 
                <p class="text-muted">@Translate("Are you sure you want to delete the list") <strong id="deleteFavoriteName"></strong> @Translate("and its content?")</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dw-button="secondary" data-bs-dismiss="modal">@Translate("Cancel")</button>
                <button type="button" class="btn btn-primary" data-dw-button="primary" id="deleteFavoriteListButton">@Translate("Delete list")</button>
            </div>
        </div>
    </div>
</div>

<script>
    let userId = @userId;
    let renameFavoriteListModal = document.querySelector("#renameFavoriteListModal")
    let deleteFavoriteListModal = document.querySelector("#deleteFavoriteListModal")

    renameFavoriteListModal.addEventListener('show.bs.modal', function (event) {
        let button = event.relatedTarget
        let renameFavoriteListId = button.getAttribute('data-list-id');
        let renameFromName = button.getAttribute('data-list-name')
        let renameFavoriteListInputName = document.getElementById('renameFavoriteListInputName');

        renameFavoriteListInputName.value = renameFromName;

        document.querySelector("#renameFavoriteListButton").addEventListener("click", function () {
            let favoriteListId = renameFavoriteListId;

            // Rename Favorite List
            document.location.href = "/Default.aspx?ID=@(Pageview.Page.ID)&favoritecmd=renamefavoritelist&userId=" + userId + "&favoriteListId=" + favoriteListId + "&name=" + encodeURIComponent(renameFavoriteListInputName.value);
        });
    })

    deleteFavoriteListModal.addEventListener('show.bs.modal', function (event) {
        let button = event.relatedTarget;
        let deleteFavoriteListId = button.getAttribute('data-list-id');
        let deleteFavoriteListName = button.getAttribute('data-list-name');
        let deleteFavoriteName = document.querySelector("#deleteFavoriteName");

        // Update label to confirm before deletion
        deleteFavoriteName.textContent = deleteFavoriteListName;

        // Delete Favorite List
        document.querySelector("#deleteFavoriteListButton").addEventListener("click", function () {
            let favoriteListId = deleteFavoriteListId;
            DeleteFavoriteList(userId, favoriteListId);
        });
    })

    async function DeleteFavoriteList(userId, favoriteListId) {
        var url = "/Default.aspx?ID=@(Pageview.Page.ID)&favoritecmd=removefavoritelist&userId=" + userId + "&favoriteListId=" + favoriteListId;

        let response = await fetch(url);
        if (response.ok) {
            document.location.href = "/Default.aspx?ID=@(Pageview.Page.ID)";
        }
    }

    // Create new Favorite List
    document.querySelector("#createFavoriteListButton").addEventListener("click", function () {
        let createFavoriteListName = document.querySelector("#createFavoriteListInputName").value;

        if (createFavoriteListName != "") {
            document.location.href = "/Default.aspx?ID=@(Pageview.Page.ID)&favoritecmd=createfavoritelist&userId=" + userId + "&name=" + encodeURIComponent(createFavoriteListName);
        }
        else if (document.querySelector("#createFavoriteListError")) {
            document.querySelector("#createFavoriteListError").classList.remove("d-none");
        }
    });
</script>