<script>
    import api from "$lib/axios";
    import clsx from "clsx";
    import { v4 as uuidv4 } from "uuid";
    import { goto } from "$app/navigation";
    import { onMount } from "svelte";

    export let modal;
    export let handleGetRules;

    let form;
    let isLoadingOnSubmit = false;
    let conditions = [];
    let confidence = 50;
    let followUpQuestions = [];
    let selectedSymptoms = [];
    let diseases = [];
    let symptoms = [];
    let alert = {
        success: true,
        message: "",
    };

    const handleGetDiseases = async () => {
        try {
            const response = await api.get(`/diseases`);
            diseases = response.data?.data;
        } catch (err) {
            console.error(err);
        }
    };

    const handleGetSymptoms = async () => {
        try {
            const response = await api.get(`/symptoms`);
            symptoms = response.data?.data;
        } catch (err) {
            console.error(err);
        }
    };

    const handleSubmit = async () => {
        try {
            isLoadingOnSubmit = true;

            const fd = new FormData(form);
            const response = await api.post(`/rules`, {
                ...Object.fromEntries(fd),
                confidence,
                symptoms_id: selectedSymptoms.map((item) => item.id),
                follow_up_questions: conditions.map(
                    (con) => `${con.follow_up_question.question}: ${con.follow_up_value}`,
                ),
            });

            alert.success = true;
            alert.message = "";

            handleGetRules();
            setTimeout(() => modal.hide(), 500);
        } catch (err) {
            alert.success = false;
            alert.message = err.message;
        } finally {
            isLoadingOnSubmit = false;
        }
    };

    onMount(() => {
        const bm = document.querySelector("#create-rule-modal");
        bm.addEventListener("shown.bs.modal", () => {
            handleGetDiseases();
            handleGetSymptoms();
        });
        bm.addEventListener("hide.bs.modal", () => {
            setTimeout(() => {
                alert.message = "";
                confidence = 50;
                followUpQuestions = [];
                selectedSymptoms = [];
                conditions = [];
                form.reset();
            }, 500);
        });
    });
</script>

<div
    id="create-rule-modal"
    class="modal fade"
    data-bs-backdrop="static"
    data-bs-keyboard="false"
    tabindex="-1"
    aria-hidden="true"
>
    <div class="modal-dialog modal-dialog-centered">
        <form action="" method="post" class="modal-content" bind:this={form} on:submit|preventDefault={handleSubmit}>
            <div class="modal-header">
                <h5 class="modal-title">Relasi Baru</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                {#if alert.message}
                    <div class="alert alert-danger alert-dismissible" role="alert">
                        <div class="alert-icon">
                            <i class="ti ti-exclamation-circle"></i>
                        </div>
                        {alert.message}
                        <a href={"#"} class="btn-close" data-bs-dismiss="alert" aria-label="close"></a>
                    </div>
                {/if}
                <div class="mb-3">
                    <label for="input-disease" class="form-label">
                        Target Penyakit <span class="text-danger">*</span>
                    </label>
                    <select name="disease_id" id="input-disease" class="form-select" required>
                        <option value="">Pilih penyakit ...</option>
                        {#each diseases as disease}
                            <option value={disease.id}>{disease?.name || ""}</option>
                        {/each}
                    </select>
                </div>
                <div class="mb-3">
                    <label for="input-confidence" class="form-label d-flex justify-content-between">
                        <div class="">
                            Konfidensi <span class="text-danger">*</span>
                        </div>
                        <div class="">{confidence}%</div>
                    </label>
                    <input
                        type="range"
                        name="confidence"
                        id="input-confidence"
                        class="form-range"
                        value="50"
                        min="0"
                        max="100"
                        step="1"
                        required
                        on:input={(e) => {
                            confidence = Number(e.target.value);
                        }}
                    />
                </div>
                <div class="mb-3">
                    <div class="card">
                        <div class="card-header">
                            <label for="input-description" class="form-label mb-0">
                                Gejala
                                <span class="badge bg-primary-lt">{selectedSymptoms.length} dipilih</span>
                            </label>
                        </div>
                        <div class="table-responsive" style="height: 200px;">
                            <table class="table table-hover table-selectable card-table table-vcenter text-nowrap">
                                <tbody>
                                    {#each symptoms as symptom}
                                        {@const categories = {
                                            danger: "danger",
                                            respiratory: "warning",
                                            digestive: "lime",
                                            general: "primary",
                                            skin: "purple",
                                            specific: "secondary",
                                        }}
                                        <tr
                                            class={selectedSymptoms.find((item) => item.id === symptom.id)
                                                ? "bg-primary-lt"
                                                : ""}
                                        >
                                            <th>
                                                <input
                                                    type="checkbox"
                                                    name=""
                                                    id=""
                                                    class="form-check m-0"
                                                    on:input={() => {
                                                        if (selectedSymptoms.find((item) => item.id === symptom.id)) {
                                                            return (selectedSymptoms = selectedSymptoms.filter(
                                                                (prev) => prev.id !== symptom.id,
                                                            ));
                                                        }
                                                        selectedSymptoms = [...selectedSymptoms, symptom];
                                                    }}
                                                />
                                            </th>
                                            <td>{symptom.name}</td>
                                            <td>
                                                <span
                                                    class={clsx(
                                                        "badge",
                                                        "text-capitalize",
                                                        `bg-${categories[symptom.category]}-lt`,
                                                    )}>{symptom.category}</span
                                                >
                                            </td>
                                            <td
                                                ><span class="badge bg-secondary-lt"
                                                    >{symptom?.follow_up_questions?.length || "0"}</span
                                                ></td
                                            >
                                        </tr>
                                    {/each}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="mb-3 d-flex align-items-center gap-2">
                    <div class="">
                        <strong>Kondisi Tambahan</strong>
                    </div>
                    <div class="flex-grow-1"></div>
                    <div class="">
                        <button
                            type="button"
                            class="btn"
                            on:click={() => {
                                conditions = [
                                    ...conditions,
                                    {
                                        id: uuidv4(),
                                        symptom: null,
                                        follow_up_question: null,
                                        follow_up_value: "",
                                    },
                                ];
                            }}
                        >
                            <i class="ti ti-plus me-2"></i>
                            Tambah Kondisi
                        </button>
                    </div>
                </div>
                <div class="d-flex flex-column gap-3">
                    {#each conditions as condition, i}
                        <div class="card" id={condition.id}>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label for="input-follow-up-question" class="form-label d-flex gap-2">
                                        <div class="">
                                            Gejala <span class="text-danger">*</span>
                                        </div>
                                        <div class="flex-grow-1"></div>
                                        <div class="">
                                            <button
                                                type="button"
                                                class="btn-close"
                                                aria-label="Condition Close"
                                                on:click={() => {
                                                    conditions = conditions.filter((item) => item.id !== condition.id);
                                                }}
                                            ></button>
                                        </div>
                                    </label>
                                    <select
                                        name=""
                                        id=""
                                        class="form-select"
                                        value={condition?.symptom?.id || ""}
                                        on:input={(e) => {
                                            conditions = conditions.map((item) => {
                                                if (item.id === condition.id) {
                                                    return {
                                                        ...item,
                                                        symptom: selectedSymptoms.find(
                                                            (symp) => symp.id === e.target.value,
                                                        ),
                                                    };
                                                }
                                                return item;
                                            });
                                        }}
                                    >
                                        <option value="">Pilih Gejala ...</option>
                                        {#each selectedSymptoms as selectedSymptom}
                                            <option value={selectedSymptom.id}>{selectedSymptom.name}</option>
                                        {/each}
                                    </select>
                                </div>
                                <div class="row g-3 mb-3">
                                    <div class="col-6">
                                        <div class="">
                                            <label for="input-type" class="form-label">
                                                Pertanyaan Tindak Lanjut <span class="text-danger">*</span>
                                            </label>
                                            <select
                                                name=""
                                                id="input-type"
                                                class="form-select"
                                                required
                                                value={condition?.follow_up_question?.question || ""}
                                                on:input={(e) => {
                                                    conditions = conditions.map((item) => {
                                                        if (item.id === condition.id) {
                                                            return {
                                                                ...item,
                                                                follow_up_question:
                                                                    condition.symptom.follow_up_questions.find(
                                                                        (fuq) => fuq.question === e.target.value,
                                                                    ),
                                                            };
                                                        }
                                                        return item;
                                                    });
                                                }}
                                            >
                                                <option value="">Pilih tindak lanjut ...</option>
                                                {#each condition.symptom?.follow_up_questions as question}
                                                    <option value={question.question}>{question.question}</option>
                                                {/each}
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="">
                                            <label for="input-type" class="form-label">
                                                Opsi <span class="text-danger">*</span>
                                            </label>
                                            <select
                                                name=""
                                                id="input-type"
                                                class="form-select"
                                                required
                                                value={condition?.follow_up_value || ""}
                                                on:input={(e) => {
                                                    conditions = conditions.map((item) => {
                                                        if (item.id === condition.id) {
                                                            return {
                                                                ...item,
                                                                follow_up_value: e.target.value,
                                                            };
                                                        }
                                                        return item;
                                                    });
                                                }}
                                            >
                                                <option value="">Pilih opsi ...</option>
                                                {#each condition?.follow_up_question?.options as option}
                                                    <option value={option}>{option}</option>
                                                {/each}
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    {/each}
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn me-auto" data-bs-dismiss="modal">Batal</button>
                <button type="submit" class="btn btn-primary" disabled={isLoadingOnSubmit}>
                    {#if isLoadingOnSubmit}
                        <div class="spinner-border spinner-border-sm" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    {:else}
                        Simpan
                    {/if}
                </button>
            </div>
        </form>
    </div>
</div>
