<script>
    import { createEventDispatcher } from "svelte";
    const dispatch = createEventDispatcher();
    import { range } from "lodash";
    import NavItem from "./NavItem.svelte";
    export let inModal;
    export let modalUrl;
    export let limit;
    export let skip;
    export let total;

    $: totalPages = Math.ceil(total / limit);
    $: currentPage = Math.ceil((skip - 1) / limit) + 1;

    $: pageRange = range(currentPage - 3, currentPage + 4).filter((i) => {
        return i > 0 && i <= totalPages;
    });

    function last(e) {
        e.preventDefault();
        goto(totalPages);
    }
    function first(e) {
        e.preventDefault();
        goto(1);
    }
    function page(e, page) {
        e.preventDefault();
        goto(page);
    }

    function goto(page) {
        const url = new URL(modalUrl ?? window.location.href);
        let skip = page * limit - limit;
        url.searchParams.set("skip", skip);

        if (inModal) {
            dispatch("refresh", url);
        } else {
            window.location = url;
        }
    }
</script>

<nav>
    <ul class="pagination justify-content-center">
        {#if totalPages > 1}
            <li class="page-item disabled" class:disabled={currentPage === 1}>
                <a on:click={first} href="/" class="page-link"> First </a>
            </li>

            <NavItem
                pages={pageRange}
                {currentPage}
                {limit}
                {inModal}
                {modalUrl}
                on:refresh
            />

            <li class="page-item">
                <a
                    on:click={last}
                    class="page-link"
                    href="/"
                    class:disabled={currentPage === totalPages}>Last</a
                >
            </li>
        {/if}
    </ul>
</nav>
<p class="text-muted text-center">
    Showing
    <span class="font-medium">{+skip + 1}</span>
    to
    <span class="font-medium"
        >{+skip + limit > total ? total : +skip + limit}</span
    >
    of
    <span class="font-medium">{total}</span>
    total
</p>
