<script>
    import CreateDiseases from "./CreateDiseases.svelte";
    import Detail from "./Detail.svelte";
    import EmptyState from "$components/EmptyState.svelte";
    import Pagination from "$components/Pagination.svelte";
    import Loader from "$components/Loader.svelte";
    import api from "$lib/axios";
    import clsx from "clsx";
    import { onMount } from "svelte";
    import { Modal } from "$lib/modal";

    let createDiseaseModal = new Modal("#create-diseases-modal");
    let detailDiseaseModal = new Modal("#detail-diseases-modal");

    let form;
    let diseases = [];
    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 handleGetDiseases = async (page = 1, { withLoading = true } = {}) => {
        try {
            if (withLoading) {
                isLoading = true;
            }

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

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

    const showDetailModal = (disease) => {
        detailDiseaseModal.disease = disease;
        detailDiseaseModal.show();
    };

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

<CreateDiseases modal={createDiseaseModal} {handleGetDiseases} />

<Detail modal={detailDiseaseModal} {handleGetDiseases} />

<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;
                    handleGetDiseases();
                }}
            >
                <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={() => createDiseaseModal.show()}>
                <i class="ti ti-plus me-2"></i>
                Tambah Penyakit
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        {#if !isLoading}
            {#if diseases.length > 0}
                <div class="table-responsive">
                    <table class="table table-hover table-selectable card-table table-vcenter text-nowrap">
                        <thead>
                            <tr>
                                <th scope="col" class="">No</th>
                                <th scope="col" class="">Nama</th>
                                <th scope="col" class="">Deskripsi</th>
                                <th scope="col" class="">Tingkat Keparahan</th>
                                <th scope="col" class="">Rekomendasi Penanganan</th>
                                <th scope="col" class="text-end">Dibuat</th>
                                <th scope="col" class="text-end">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            {#each diseases as disease, i}
                                {@const severity = {
                                    severe: ["danger", "Berat"],
                                    moderate: ["warning", "Sedang"],
                                    mild: ["primary", "Ringan"],
                                }}
                                <tr class={clsx(disease.severity === "severe" ? "bg-danger-lt" : "")}>
                                    <th scope="row">{(pagination.current_page - 1) * pagination.limit + (i + 1)}</th>
                                    <th>{disease?.name || ""}</th>
                                    <td>
                                        <div class="text-truncate" style="max-width: 350px;">
                                            {disease?.description || ""}
                                        </div>
                                    </td>
                                    <td class="">
                                        <span
                                            class={clsx(
                                                "badge",
                                                "text-capitalize",
                                                `bg-${severity[disease.severity][0]}-lt`,
                                            )}>{severity[disease.severity][1]}</span
                                        >
                                    </td>
                                    <td class="">
                                        <div class="text-truncate" style="max-width: 350px;">
                                            {disease?.treatment || ""}
                                        </div>
                                    </td>
                                    <td class="text-end">
                                        {disease.created_at ? window.moment(disease.created_at).format("LL") : ""}
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-list flex-nowrap">
                                            <button
                                                type="button"
                                                class="btn btn-sm btn-primary"
                                                aria-label="Lihat detail penyakit"
                                                on:click={() => {
                                                    showDetailModal(disease);
                                                }}
                                                title="Lihat detail penyakit"
                                            >
                                                <i class="ti ti-eye"></i>
                                            </button>
                                        </div>
                                    </td></tr
                                >
                            {/each}
                        </tbody>
                    </table>
                </div>
            {:else}
                <EmptyState height="250px" />
            {/if}
        {:else}
            <Loader height="250px" />
        {/if}
    </div>

    {#if diseases.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;
                    handleGetDiseases(e.detail.page);
                }}
            />
        </div>
    {/if}
</div>
