<script>
    import Result from "./Result.svelte";
    import Summary from "./Summary.svelte";
    import clsx from "clsx";
    import api from "$lib/axios";
    import { page } from "$app/stores";
    import { onMount } from "svelte";

    let patientId = $page.params.id;
    let symptoms = [];
    let currentSymptom = {};
    let finish = false;
    let result = null;
    let summaries = [];
    let isLoading = false;
    let index = 0;
    let followUpQuestionsIsOpen = false;
    let followUpQuestions = [];
    let alert = {
        success: true,
        message: "",
    };

    const handleGetSymptoms = async () => {
        try {
            const response = await api.get(`/symptoms`);

            symptoms = response.data?.data;
            currentSymptom = symptoms[index];
        } catch (err) {
            alert.success = false;
            alert.message = err.message;
        } finally {
            isLoading = false;
        }
    };

    const handleDiagnose = async () => {
        try {
            const response = await api.post(`/diagnoses/${patientId}`, {
                symptoms_id: summaries.filter((item) => item.ok).map((item) => item.id),
                follow_up_questions: followUpQuestions,
            });

            if (!response.data?.data && index < symptoms.length - 1) {
                index += 1;
                currentSymptom = symptoms[index];
            } else {
                finish = true;
                index = symptoms.length;
                currentSymptom = {};
                result = response.data?.data;
            }
        } catch (err) {
            alert.success = false;
            alert.message = err.message;
        } finally {
            followUpQuestionsIsOpen = false;
        }
    };

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

<div class="d-flex justify-content-center">
    <div class="w-100" style="max-width: 640px;">
        <div class="d-flex gap-2">
            <h5 class="card-title">Progres Diagnosa</h5>
            <div class="flex-grow-1"></div>
            <div class="">{((index / symptoms.length) * 100).toFixed(0)}%</div>
        </div>
        <div class="progress">
            <div
                class={clsx(
                    "progress-bar",
                    finish || ((index / symptoms.length) * 100).toFixed(0) >= 100 ? "bg-success" : "bg-primary",
                )}
                role="progressbar"
                style="width: {((index / symptoms.length) * 100).toFixed(0)}%;"
                aria-valuenow="25"
                aria-valuemin="0"
                aria-valuemax="100"
            ></div>
        </div>
        <p class="mt-3">
            Langkah {index >= symptoms.length ? index : index + 1} dari maksimal {symptoms.length} pertanyaan
        </p>
        {#if !finish}
            <div class="card mt-5">
                <div class="card-header">
                    <h5 class="card-title">Pertanyaan {index + 1}</h5>
                </div>
                <div class="card-body">
                    <div class={clsx("alert", currentSymptom.category === "danger" ? "alert-danger" : "alert-primary")}>
                        <div class="">
                            <h3 class={currentSymptom.category === "danger" ? "text-danger" : "text-primary"}>
                                {currentSymptom.question}
                            </h3>
                            <p class="mb-0">{currentSymptom.description}</p>
                        </div>
                    </div>
                </div>
                <div class="card-footer d-flex justify-content-center gap-2">
                    <button
                        type="button"
                        class={clsx("btn", currentSymptom.category === "danger" ? "btn-danger" : "btn-primary")}
                        disabled={followUpQuestionsIsOpen}
                        style="width: 150px;"
                        on:click={() => {
                            if (currentSymptom?.follow_up_questions?.length > 0) {
                                followUpQuestionsIsOpen = true;
                                return;
                            }

                            summaries = [
                                ...summaries,
                                {
                                    ...currentSymptom,
                                    ok: true,
                                },
                            ];

                            handleDiagnose();
                        }}>Ya</button
                    >
                    <button
                        type="button"
                        class="btn"
                        disabled={followUpQuestionsIsOpen}
                        style="width: 150px;"
                        on:click={() => {
                            summaries = [
                                ...summaries,
                                {
                                    ...currentSymptom,
                                    ok: false,
                                },
                            ];

                            if (index + 1 >= symptoms.length) {
                                index = symptoms.length;
                                currentSymptom = {};
                                finish = true;
                                result = null;
                                return;
                            }

                            index += 1;
                            currentSymptom = symptoms[index];
                        }}>Tidak</button
                    >
                </div>
            </div>
            {#if followUpQuestionsIsOpen && currentSymptom?.follow_up_questions?.length > 0}
                <div class="card mt-3">
                    <div class="card-header">
                        <h5 class="card-title">Pertanyaan 3: Lanjutan</h5>
                    </div>
                    <div class="card-body">
                        {#each currentSymptom.follow_up_questions as followUpQuestion}
                            <div
                                class={clsx(
                                    "alert",
                                    "d-grid",
                                    "gap-3",
                                    currentSymptom.category === "danger" ? "alert-danger" : "alert-primary",
                                )}
                            >
                                <h3 class={currentSymptom.category === "danger" ? "text-danger" : "text-primary"}>
                                    {followUpQuestion.question}
                                </h3>
                                <div class="form-selectgroup form-selectgroup-boxes d-flex flex-column">
                                    {#each followUpQuestion.options as question}
                                        <label class="form-selectgroup-item flex-fill">
                                            <input
                                                type="radio"
                                                name={followUpQuestion.id}
                                                value={question || ""}
                                                class="form-selectgroup-input"
                                                on:input={(e) => {
                                                    const prev = followUpQuestions.find(
                                                        (item) => item.id === followUpQuestion.id,
                                                    );

                                                    if (prev) {
                                                        followUpQuestions = followUpQuestions.map((q) => {
                                                            if (q.id === followUpQuestion.id) {
                                                                q.symptom_id = currentSymptom.id;
                                                                q.option = e.target.value;
                                                            }
                                                            return q;
                                                        });
                                                    } else {
                                                        followUpQuestions = [
                                                            ...followUpQuestions,
                                                            {
                                                                ...followUpQuestion,
                                                                symptom_id: currentSymptom.id,
                                                                option: e.target.value,
                                                            },
                                                        ];
                                                    }
                                                }}
                                            />
                                            <div class="form-selectgroup-label d-flex align-items-center p-3">
                                                <div class="me-3">
                                                    <span class="form-selectgroup-check"></span>
                                                </div>
                                                <div>
                                                    <span class="payment payment-provider-visa payment-xs me-2"></span>
                                                    {question || ""}
                                                </div>
                                            </div>
                                        </label>
                                    {/each}
                                </div>
                            </div>
                        {/each}
                    </div>
                    <div class="card-footer d-flex justify-content-center gap-2">
                        <button
                            type="button"
                            class={clsx("btn", currentSymptom.category === "danger" ? "btn-danger" : "btn-primary")}
                            style="width: 150px;"
                            on:click={() => {
                                summaries = [
                                    ...summaries,
                                    {
                                        ...currentSymptom,
                                        ok: true,
                                    },
                                ];

                                handleDiagnose();
                            }}>Simpan</button
                        >
                        <button
                            type="button"
                            class="btn"
                            style="width: 150px;"
                            on:click={() => {
                                followUpQuestionsIsOpen = false;
                            }}>Batal</button
                        >
                    </div>
                </div>
            {/if}
            <Summary {summaries} />
        {/if}

        {#if finish}
            <Result {result} />
            {#if finish && !result}
                <Summary {summaries} />
            {/if}
        {/if}
    </div>
</div>
