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

    export let modal;
    export let handleGetPatients;

    let form;
    let birthDate = "";
    let isBirthDateValid = true;
    let isLoadingOnSubmit = false;
    let alert = {
        success: true,
        message: "",
    };

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

            const fd = new FormData(form);
            const response = await api.post(`/patients`, Object.fromEntries(fd));

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

            handleGetPatients();
            modal.hide();
            goto(`/staff/patients/${response.data.data.id}`);
        } catch (err) {
            alert.success = false;
            alert.message = err.message;
        } finally {
            isLoadingOnSubmit = false;
        }
    };

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

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

<div
    id="create-patient-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">Pasien 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-fullname" class="form-label">
                        Nama Lengkap Balita <span class="text-danger">*</span>
                    </label>
                    <input
                        type="text"
                        name="fullname"
                        id="input-fullname"
                        class="form-control"
                        placeholder=""
                        required
                    />
                </div>
                <div class="mb-3">
                    <label for="input-gender" class="form-label">
                        Jenis Kelamin <span class="text-danger">*</span>
                    </label>
                    <select name="gender" id="input-gender" class="form-select" required>
                        <option value="" disabled selected>Pilih jenis kelamin</option>
                        <option value="male">Laki-laki</option>
                        <option value="female">Perempuan</option>
                    </select>
                </div>
                <div class="mb-2">
                    <label for="input-birth-date" class="form-label">
                        Tanggal Lahir <span class="text-danger">*</span>
                    </label>
                    <input
                        type="date"
                        name="birth_date"
                        id="input-birth-date"
                        class={clsx("form-control", birthDate ? (isBirthDateValid ? "is-valid" : "is-invalid") : "")}
                        placeholder=""
                        required
                        on:input={(e) => {
                            birthDate = e.target.value;
                            const { y, m } = age(window.moment(birthDate));

                            isBirthDateValid = (y === 0 && m >= 2) || (y > 0 && y < 5);
                        }}
                    />
                </div>
                {#if birthDate}
                    {@const { y, m } = age(window.moment(birthDate))}
                    <div
                        class={clsx("alert", "mb-0", isBirthDateValid ? "alert-success" : "alert-danger")}
                        role="alert"
                    >
                        <div class="alert-icon">
                            <i class={clsx("ti", "mb-0", isBirthDateValid ? "ti-check" : "ti-exclamation-circle")}></i>
                        </div>
                        <div class="">
                            <h4 class="alert-heading">{`Usia: ${y} Tahun ${m} Bulan.`}</h4>
                            {#if isBirthDateValid}
                                <div class="alert-description">Usia memenuhi kriteria. Lanjutkan proses.</div>
                            {:else}
                                <div class="alert-description">
                                    Usia pasien tidak memenuhi kriteria. Rentang usia yang diperbolehkan adalah antara 2
                                    bulan hingga 5 tahun.
                                </div>
                            {/if}
                        </div>
                    </div>
                {/if}
            </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>
