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

    let patient = {};
    let patientId = $page.params.id;
    let isLoading = false;
    let diagnose = null;
    let alert = { success: true, message: "" };

    onMount(() => {
        handleGetPatient();
        handleGetDiagnose();
    });

    const handleGetPatient = async () => {
        try {
            const response = await api.get(`/patients/${patientId}`);
            patient = response.data?.data;
        } catch (err) {
            alert.success = false;
            alert.message = err.message;
        }
    };

    const handleGetDiagnose = async () => {
        try {
            const response = await api.get(`/diagnoses/${patientId}`);
            diagnose = response.data?.data;
        } catch (err) {
            alert.success = false;
            alert.message = err.message;
        }
    };

    function age(date) {
        const today = new Date();
        const birth = new Date(date);
        let y = today.getFullYear() - birth.getFullYear();
        let m = today.getMonth() - birth.getMonth();
        if (m < 0) {
            y--;
            m += 12;
        }
        return { y, m };
    }

    $: id = $page.params.id;

    async function downloadPdf() {
        const res = await fetch(`/staff/patients/${id}/pdf`);

        if (!res.ok) {
            window.alert(await res.text());
            return;
        }
        const blob = await res.blob();
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `diagnosa-${id}.pdf`;
        a.click();
        URL.revokeObjectURL(url);
    }
</script>

<div class="card">
    <div class="card-header flex-wrap gap-2">
        <div class="">
            <h5 class="card-title d-flex align-items-center">
                <i class="ti ti-file-text me-2"></i>
                Informasi Pasien
            </h5>
        </div>
        <div class="flex-grow-1"></div>
        <div class="">
            <button type="button" class="btn" on:click={downloadPdf}>
                <i class="ti ti-printer me-2"></i>
                Cetak
            </button>
        </div>
    </div>

    <div>
        <div class="card-body">
            <table class="table table-borderless">
                <thead>
                    <tr>
                        <th>Nama Lengkap</th>
                        <th>Usia</th>
                        <th>Tanggal Lahir</th>
                        <th>Jenis Kelamin</th>
                        <th class="text-end">Didaftarkan Oleh</th>
                        <th class="text-end">Tanggal Daftar</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th>{patient?.fullname || ""}</th>
                        <th>
                            {patient?.birth_date
                                ? age(patient.birth_date).y > 0
                                    ? `${age(patient.birth_date).y} Tahun ${age(patient.birth_date).m} Bulan`
                                    : `${age(patient.birth_date).m} Bulan`
                                : ""}
                        </th>
                        <th>
                            {patient?.birth_date ? window.moment(patient.birth_date).format("LL") : ""}
                        </th>
                        <th>
                            {#if patient.gender == "male"}
                                <span class="badge bg-primary-lt">Laki-Laki</span>
                            {:else}
                                <span class="badge bg-pink-lt">Perempuan</span>
                            {/if}
                        </th>
                        <th class="text-end">{patient?.created_by?.username || ""}</th>
                        <th class="text-end">
                            {patient.created_at ? window.moment(patient.created_at).format("LL") : ""}
                        </th>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="card mt-3">
            <div class="card-header">
                <h5 class="card-title d-flex align-items-center">
                    <i class="ti ti-stethoscope me-2"></i>
                    Hasil Diagnosa
                </h5>
            </div>
            <div class="card-body">
                {#if !diagnose}
                    <div class="d-flex justify-content-center align-items-center" style="height: 150px;">
                        <a href={`/staff/patients/${$page.params.id}/diagnose`} class="btn btn-primary">
                            <i class="ti ti-health-recognition me-2"></i>
                            Periksa Sekarang
                        </a>
                    </div>
                {:else}
                    <div class="list-group">
                        <div class="list-group-item list-group-item-action active" aria-current="true">
                            <h3>{diagnose?.disease?.name}</h3>
                            <p class="mb-0">{diagnose?.disease?.description}</p>
                        </div>
                        <div class="list-group-item list-group-item-action" aria-current="true">
                            <h5 class="mb-1">Rekomendasi Penanganan</h5>
                            <h3 class="mb-0 mt-3">{diagnose?.disease?.treatment}</h3>
                        </div>
                        <div class="list-group-item list-group-item-action" aria-current="true">
                            <h5 class="mb-1">Alur Diagnosa</h5>
                            <ul class="steps steps-vertical border-0 m-0 mt-3 p-0">
                                {#each diagnose?.symptoms as symptom}
                                    <li class="step-item">
                                        <div class="h4 m-0">{symptom?.name || ""}</div>
                                        <div class="text-secondary">{symptom?.description || ""}</div>

                                        {#if diagnose.follow_up_questions?.length > 0 && diagnose.follow_up_questions?.filter((item) => item.symptom_id === symptom.id)?.length > 0}
                                            <div class="html2pdf__page-break"></div>

                                            <ul
                                                class="steps steps-yellow steps-vertical border-0 m-0 mt-3 p-0 text-yellow"
                                            >
                                                {#each diagnose.follow_up_questions?.filter((item) => item.symptom_id === symptom.id) as quest}
                                                    <li class="step-item">
                                                        <div class="text-yellow">{`${quest?.question}:`}</div>
                                                        <div class="strong m-0">{quest?.option || ""}</div>
                                                    </li>
                                                {/each}
                                            </ul>
                                        {/if}
                                    </li>
                                {/each}
                            </ul>
                        </div>
                    </div>
                {/if}
            </div>
        </div>
    </div>
</div>

<style>
    .html2pdf__page-break {
        break-before: page;
    }
    @media print {
        .html2pdf__page-break {
            break-before: page;
        }
    }
</style>
