<script lang="ts">
    import paginate from "$lib/paginate";
    import clsx from "clsx";
    import { createEventDispatcher } from "svelte";

    export let pagination = {
        current_page: 1,
        limit: 10,
        page_size: 0,
        data_size: 0,
        prev: 0,
        next: 0,
    };

    const dispatch = createEventDispatcher();
    const handleUpdate = (page: number) => dispatch("update", { page });
    const handleMovePage = (page: number | string) => {
        if (page !== "...") {
            handleUpdate(Number(page));
        }
    };
</script>

<nav class={$$props.class}>
    <div class="row gx-3 align-items-center fs-9">
        <div class="col-6">
            <span>
                Showing <strong
                    >{pagination.data_size > 0 ? (pagination.current_page - 1) * pagination.limit + 1 : 0}</strong
                >-<strong>
                    {pagination.current_page * pagination.limit > pagination.data_size
                        ? pagination.data_size
                        : pagination.current_page * pagination.limit}
                </strong>
                of <strong>{pagination.data_size}</strong> Data
            </span>
        </div>
        <div class="col-6">
            <ul class="pagination justify-content-end m-0">
                <li class="page-item">
                    <a
                        href={"#"}
                        aria-label="Pagination Prev Button"
                        class={clsx("page-link", !pagination.prev ? "disabled" : "")}
                        on:click|preventDefault={() => {
                            if (pagination.prev) handleMovePage(pagination.prev);
                        }}
                    >
                        <i class="ti ti-chevron-left"></i>
                    </a>
                </li>
                {#each paginate(pagination.current_page, pagination.page_size) as item}
                    <li class="page-item">
                        <a
                            href={"#"}
                            class="page-link {item.active ? 'active' : ''}"
                            on:click|preventDefault={() => {
                                handleMovePage(item.name);
                            }}
                        >
                            {item.name}
                        </a>
                    </li>
                {/each}
                <li class="page-item">
                    <a
                        href={"#"}
                        aria-label="Pagination Next Button"
                        class={clsx("page-link", !pagination.next ? "disabled" : "")}
                        on:click|preventDefault={() => {
                            if (pagination.next) handleMovePage(pagination.next);
                        }}
                    >
                        <i class="ti ti-chevron-right"></i>
                    </a>
                </li>
            </ul>
        </div>
    </div>
</nav>
