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

    let createRuleModal = new Modal("#create-rule-modal");
    let detailRuleModal = new Modal("#detail-rule-modal");

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

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

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

    const handleShowDetail = (rule) => {
        detailRuleModal.rule = rule;
        detailRuleModal.show();
    };

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

<CreateRule modal={createRuleModal} {handleGetRules} />
<DetailRule modal={detailRuleModal} {handleGetRules} />

<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;
                    handleGetRules();
                }}
            >
                <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={() => createRuleModal.show()}>
                <i class="ti ti-plus me-2"></i>
                Tambah Relasi
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        {#if !isLoading}
            {#if rules.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="">Gejala Klinis</th>
                                <th scope="col" class="">konfidensi</th>
                                <th scope="col" class="text-end">Dibuat</th>
                                <th scope="col" class="text-end">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            {#each rules as rule, i}
                                <tr class={clsx(rule?.disease?.severity === "severe" ? "bg-danger-lt" : "")}>
                                    <th scope="row">{(pagination.current_page - 1) * pagination.limit + (i + 1)}</th>
                                    <th>{rule?.disease?.name || ""}</th>
                                    <td>
                                        <div class="text-truncate" style="max-width: 350px;">
                                            {rule?.disease?.description || ""}
                                        </div>
                                    </td>
                                    <td>
                                        <div class="d-flex flex-wrap gap-1" style="max-width: 350px;">
                                            {#each rule.symptoms as symptom}
                                                <span
                                                    class={clsx(
                                                        "badge",
                                                        symptom.category === "danger"
                                                            ? "bg-danger-lt"
                                                            : "bg-secondary-lt",
                                                    )}>{symptom?.name || ""}</span
                                                >
                                            {/each}
                                        </div>
                                    </td>
                                    <td>
                                        <span class="fw-bold text-primary">
                                            {rule?.confidence}%
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        {rule.created_at ? window.moment(rule.created_at).format("LL") : ""}
                                    </td>
                                    <td class="text-center">
                                        <button
                                            type="button"
                                            class="btn btn-sm btn-primary"
                                            on:click={() => handleShowDetail(rule)}
                                            title="Lihat Detail Relasi"
                                            aria-label="Lihat Detail Relasi"
                                        >
                                            <i class="ti ti-eye"></i>
                                        </button>
                                    </td>
                                </tr>
                            {/each}
                        </tbody>
                    </table>
                </div>
            {:else}
                <EmptyState height="250px" />
            {/if}
        {:else}
            <Loader height="250px" />
        {/if}
    </div>

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