<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 handleGetSymptoms;

    let form;
    let isLoadingOnSubmit = false;
    let followUpQuestions = [];
    let alert = {
        success: true,
        message: "",
    };

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

            console.log(followUpQuestions);

            const fd = new FormData(form);
            const response = await api.post(`/symptoms`, {
                ...Object.fromEntries(fd),
                follow_up_questions: followUpQuestions?.map((quest) => ({
                    ...quest,
                    options: quest?.options?.split(", ") || [],
                })),
            });

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

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

    onMount(() => {
        const bm = document.querySelector("#create-symptom-modal");
        bm.addEventListener("hide.bs.modal", () => {
            setTimeout(() => {
                alert.message = "";
                followUpQuestions = [];
                form.reset();
            }, 500);
        });
    });
</script>

<div
    id="create-symptom-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">Gejala 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="row g-3 mb-3">
                    <div class="col-7">
                        <div class="">
                            <label for="input-name" class="form-label">
                                Nama Gejala <span class="text-danger">*</span>
                            </label>
                            <input
                                type="text"
                                name="name"
                                id="input-name"
                                class="form-control"
                                placeholder=""
                                required
                            />
                        </div>
                    </div>
                    <div class="col-5">
                        <div class="">
                            <label for="input-category" class="form-label">
                                Kategori <span class="text-danger">*</span>
                            </label>
                            <select name="category" id="input-category" class="form-select" required>
                                <option value="" disabled selected>Pilih kategori</option>
                                <option value="danger">Bahaya</option>
                                <option value="respiratory">Pernapasan</option>
                                <option value="digestive">Pencernaan</option>
                                <option value="general">Umum</option>
                                <option value="skin">Kulit</option>
                                <option value="specific">Spesifik</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="input-description" class="form-label">Deskripsi</label>
                    <input
                        type="text"
                        name="description"
                        id="input-description"
                        class="form-control"
                        placeholder="Informasi singkat terkait gejala ini."
                    />
                </div>
                <div class="mb-3">
                    <label for="input-question" class="form-label">
                        Pertanyaan <span class="text-danger">*</span>
                    </label>
                    <textarea
                        name="question"
                        id="input-question"
                        class="form-control"
                        style="resize: none;"
                        placeholder="Pertanyaan yang perlu diajukan kepada pasien terkait gejala ini."
                        rows="4"
                        required
                    ></textarea>
                </div>
                <div class="mb-3 d-flex align-items-center gap-2">
                    <div class="">
                        <strong>Pertanyaan Tindak Lanjut</strong>
                    </div>
                    <div class="flex-grow-1"></div>
                    <div class="">
                        <button
                            type="button"
                            class="btn"
                            on:click={() => {
                                followUpQuestions = [
                                    ...followUpQuestions,
                                    {
                                        id: uuidv4(),
                                        question: "",
                                        type: "",
                                        options: "",
                                    },
                                ];
                            }}
                        >
                            <i class="ti ti-plus me-2"></i>
                            Tambah Pertanyaan
                        </button>
                    </div>
                </div>
                <div class="d-flex flex-column gap-3">
                    {#each followUpQuestions as quest, i}
                        <div class="card" id={quest.id}>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label for="input-follow-up-question" class="form-label d-flex gap-2">
                                        <div class="">
                                            Pertanyaan <span class="text-danger">*</span>
                                        </div>
                                        <div class="flex-grow-1"></div>
                                        <div class="">
                                            <button
                                                type="button"
                                                class="btn-close"
                                                aria-label="Follow-up Close"
                                                on:click={() => {
                                                    followUpQuestions = followUpQuestions.filter(
                                                        (item) => item.id !== quest.id,
                                                    );

                                                    console.log(followUpQuestions);
                                                }}
                                            ></button>
                                        </div>
                                    </label>
                                    <input
                                        type="text"
                                        name=""
                                        id="input-follow-up-question"
                                        class="form-control"
                                        placeholder=""
                                        required
                                        value={quest.question}
                                        on:input={(e) => {
                                            followUpQuestions = followUpQuestions.map((item) => {
                                                if (item.id === quest.id) {
                                                    return {
                                                        ...item,
                                                        question: e.target.value,
                                                    };
                                                }
                                                return item;
                                            });
                                        }}
                                    />
                                </div>
                                <div class="row g-3 mb-3">
                                    <div class="col-6">
                                        <div class="">
                                            <label for="input-type" class="form-label">
                                                Tipe <span class="text-danger">*</span>
                                            </label>
                                            <select
                                                name=""
                                                id="input-type"
                                                class="form-select"
                                                required
                                                value={quest.type}
                                                on:input={(e) => {
                                                    followUpQuestions = followUpQuestions.map((item) => {
                                                        if (item.id === quest.id) {
                                                            return {
                                                                ...item,
                                                                type: e.target.value,
                                                            };
                                                        }
                                                        return item;
                                                    });
                                                }}
                                            >
                                                <option value="" disabled selected>Pilih tipe</option>
                                                <option value="generic">Pertanyaan Umum</option>
                                                <option value="duration">Durasi</option>
                                                <option value="severity">Tingkat Keparahan</option>
                                                <option value="frequency">Frekuensi</option>
                                                <option value="yes/no">Ya/Tidak</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <div class="">
                                            <label for="input-options" class="form-label">Opsi</label>
                                            <input
                                                type="text"
                                                name=""
                                                id="input-options"
                                                class="form-control"
                                                placeholder="Pisahkan dengan koma ( , )"
                                                value={quest.options}
                                                on:input={(e) => {
                                                    followUpQuestions = followUpQuestions.map((item) => {
                                                        if (item.id === quest.id) {
                                                            return {
                                                                ...item,
                                                                options: e.target.value,
                                                            };
                                                        }
                                                        return item;
                                                    });
                                                }}
                                            />
                                        </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>
