<script>
    import CreateUser from "./CreateUser.svelte";
    import DeleteUser from "./DeleteUser.svelte";
    import UpdateUser from "./UpdateUser.svelte";
    import EmptyState from "$components/EmptyState.svelte";
    import Loader from "$components/Loader.svelte";
    import Pagination from "$components/Pagination.svelte";
    import api from "$lib/axios";
    import { Modal } from "$lib/modal";
    import { onMount } from "svelte";

    let CreateUserModal = new Modal("#create-user-modal");
    let DeleteUserModal = new Modal("#delete-user-modal");
    let UpdateUserModal = new Modal("#update-user-modal");

    let users = [];
    let currentUser = null;
    let isLoading = false;
    let searchbox = "";
    let alert = {
        success: true,
        message: "",
    };
    let pagination = {
        current_page: 1,
        limit: 10,
        page_size: 0,
        data_size: 0,
        prev: 0,
        next: 0,
    };

    const handleGetUsers = async (page = 1, { withLoading = true } = {}) => {
        try {
            if (withLoading) {
                isLoading = true;
            }

            const response = await api.get(`/users?page=${page}&limit=${pagination.limit}&search=${searchbox}`);

            pagination = response.data?.pagination;
            users = response.data?.data;
        } catch (err) {
            alert.success = false;
            alert.message = err.message;
        } finally {
            isLoading = false;
        }
    };

    onMount(() => {
        handleGetUsers();
    });
</script>

<CreateUser modal={CreateUserModal} {handleGetUsers} />
<DeleteUser modal={DeleteUserModal} context={currentUser} {pagination} {handleGetUsers} />
<UpdateUser modal={DeleteUserModal} context={currentUser} {pagination} {handleGetUsers} />

<div class="card">
    <div class="card-header flex-wrap gap-2">
        <div class="">
            <form
                action=""
                method="post"
                on:submit|preventDefault={(e) => {
                    searchbox = e.target.searchbox.value;
                    handleGetUsers();
                }}
            >
                <div class="input-icon">
                    <div class="input-icon-addon"><i class="ti ti-search"></i></div>
                    <input
                        type="search"
                        name="searchbox"
                        id="searchbox"
                        style="width: 300px;"
                        class="form-control"
                        placeholder="Cari..."
                    />
                </div>
            </form>
        </div>
        <div class="flex-grow-1"></div>
        <div class="">
            <button type="button" class="btn btn-primary" on:click={() => CreateUserModal.show()}>
                <i class="ti ti-plus me-2"></i>
                Tambah Pengguna
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        {#if !isLoading}
            {#if users.length > 0}
                <div class="table-responsive">
                    <table class="table table-selectable card-table table-vcenter text-nowrap">
                        <thead>
                            <tr>
                                <th scope="col" class="">No</th>
                                <th scope="col" class="">Nama Pengguna</th>
                                <th scope="col" class="">Email</th>
                                <th scope="col" class="">Peran</th>
                                <th scope="col" class="text-end">Dibuat</th>
                                <th scope="col" class="text-end"></th>
                            </tr>
                        </thead>
                        <tbody>
                            {#each users as user, i}
                                <tr>
                                    <th scope="row">{(pagination.current_page - 1) * pagination.limit + (i + 1)}</th>
                                    <td>{user?.username || ""}</td>
                                    <td>{user?.email || ""}</td>
                                    <td>
                                        {#if user.role == "admin"}
                                            <span class="badge bg-primary-lt">Admin</span>
                                        {:else}
                                            <span class="badge bg-warning-lt">Petugas</span>
                                        {/if}
                                    </td>
                                    <td class="text-end">
                                        {user.created_at ? window.moment(user.created_at).format("LL") : ""}
                                    </td>
                                    <td class="text-end">
                                        <div class="dropdown">
                                            <button
                                                type="button"
                                                aria-label="Dropdown Option"
                                                aria-expanded="false"
                                                data-bs-toggle="dropdown"
                                                class="btn btn-sm border-0"
                                            >
                                                <i class="ti ti-dots-vertical"></i>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li>
                                                    <a
                                                        class="dropdown-item"
                                                        href={"#"}
                                                        on:click|preventDefault={() => {
                                                            currentUser = user;
                                                            UpdateUserModal.show();
                                                        }}
                                                    >
                                                        <div class="ti ti-edit"></div>
                                                        Edit
                                                    </a>
                                                </li>
                                                <li>
                                                    <a
                                                        class="dropdown-item"
                                                        href={"#"}
                                                        on:click|preventDefault={() => {
                                                            currentUser = user;
                                                            DeleteUserModal.show();
                                                        }}
                                                    >
                                                        <i class="ti ti-trash"></i>
                                                        Hapus
                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    </td>
                                </tr>
                            {/each}
                        </tbody>
                    </table>
                </div>
            {:else}
                <EmptyState height="250px" />
            {/if}
        {:else}
            <Loader height="250px" />
        {/if}
    </div>

    {#if users.length > 0}
        <div class="card-footer border-0" style="background: var(--bs-body-bg);">
            <Pagination
                {pagination}
                on:update={(e) => {
                    pagination.current_page = e.detail.page;
                    handleGetUsers(e.detail.page);
                }}
            />
        </div>
    {/if}
</div>
