<script>
    import CreatePatient from "./CreatePatient.svelte";
    import Detail from "./Detail.svelte";
    import EmptyState from "$components/EmptyState.svelte";
    import Loader from "$components/Loader.svelte";
    import Pagination from "$components/Pagination.svelte";
    import api from "$lib/axios";
    import { Modal } from "$lib/modal";
    import { onMount } from "svelte";
    import { goto } from "$app/navigation";

    let createPatientModal = new Modal("#create-patient-modal");
    let detailPatientsModal = new Modal("#detail-patients-modal");

    let patients = [];
    let currentPatient = null;
    let isLoading = false;
    let searchbox = "";
    let alert = {
        success: true,
        message: "",
    };
    let pagination = {
        current_page: 1,
        limit: 10,
        page_size: 0,
        data_size: 0,
        prev: 0,
        next: 0,
    };

    const handleGetPatients = async (page = 1, { withLoading = true } = {}) => {
        try {
            if (withLoading) {
                isLoading = true;
            }

            const response = await api.get(`/patients?page=${page}&limit=${pagination.limit}&search=${searchbox}`);

            pagination = response.data?.pagination;
            patients = response.data?.data;
        } catch (err) {
            alert.success = false;
            alert.message = err.message;
        } finally {
            isLoading = 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 };
    }

    const showDetailModal = (patient) => {
        detailPatientsModal.patient = patient;
        detailPatientsModal.show();
    };

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

<CreatePatient modal={createPatientModal} {handleGetPatients} />

<Detail modal={detailPatientsModal} {handleGetPatients} />

<div class="card">
    <div class="card-header flex-wrap gap-2">
        <div class="">
            <form
                action=""
                method="post"
                on:submit|preventDefault={(e) => {
                    searchbox = e.target.searchbox.value;
                    handleGetPatients();
                }}
            >
                <div class="input-icon">
                    <div class="input-icon-addon"><i class="ti ti-search"></i></div>
                    <input
                        type="search"
                        name="searchbox"
                        id="searchbox"
                        style="width: 300px;"
                        class="form-control"
                        placeholder="Cari..."
                    />
                </div>
            </form>
        </div>
        <div class="flex-grow-1"></div>
        <div class="">
            <button type="button" class="btn btn-primary" on:click={() => createPatientModal.show()}>
                <i class="ti ti-plus me-2"></i>
                Tambah Pasien
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        {#if !isLoading}
            {#if patients.length > 0}
                <div class="table-responsive">
                    <table class="table table-hover table-selectable card-table table-vcenter text-nowrap">
                        <thead>
                            <tr>
                                <th scope="col" class="">No</th>
                                <th scope="col" class="">Nama Lengkap</th>
                                <th scope="col" class="">Usia</th>
                                <th scope="col" class="">Tanggal Lahir</th>
                                <th scope="col" class="">Jenis Kelamin</th>
                                <th scope="col" class="text-end">Didaftarkan Oleh</th>
                                <th scope="col" class="text-end">Tanggal Daftar</th>
                                <th scope="col" class="">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            {#each patients as patient, i}
                                {@const { y, m } = age(patient.birth_date)}
                                <tr class="cursor-pointer">
                                    <th scope="row">{(pagination.current_page - 1) * pagination.limit + (i + 1)}</th>
                                    <td
                                        on:click={() => {
                                            goto(`/staff/patients/${patient.id}`);
                                        }}
                                    >
                                        {patient?.fullname || ""}
                                    </td>
                                    <td
                                        on:click={() => {
                                            goto(`/staff/patients/${patient.id}`);
                                        }}
                                    >
                                        {patient?.birth_date ? (y > 0 ? `${y} Tahun ${m} Bulan` : `${m} Bulan`) : ""}
                                    </td>
                                    <td
                                        class=""
                                        on:click={() => {
                                            goto(`/staff/patients/${patient.id}`);
                                        }}
                                    >
                                        {patient?.birth_date ? window.moment(patient.birth_date).format("LL") : ""}
                                    </td>
                                    <td
                                        on:click={() => {
                                            goto(`/staff/patients/${patient.id}`);
                                        }}
                                    >
                                        {#if patient.gender == "male"}
                                            <span class="badge bg-primary-lt">Laki-Laki</span>
                                        {:else}
                                            <span class="badge bg-pink-lt">Perempuan</span>
                                        {/if}
                                    </td>
                                    <td
                                        class="text-end"
                                        on:click={() => {
                                            goto(`/staff/patients/${patient.id}`);
                                        }}
                                    >
                                        {patient?.created_by?.username || ""}
                                    </td>
                                    <td
                                        class="text-end"
                                        on:click={() => {
                                            goto(`/staff/patients/${patient.id}`);
                                        }}
                                    >
                                        {patient.created_at ? window.moment(patient.created_at).format("LL") : ""}
                                    </td>
                                    <td class="text-end">
                                        <div class="btn-list flex-nowrap">
                                            <button
                                                type="button"
                                                class="btn btn-sm btn-primary"
                                                aria-label="Lihat detail diagnosa pasien"
                                                on:click|stopPropagation={() => {
                                                    showDetailModal(patient);
                                                }}
                                                title="Lihat detail diagnosa pasien"
                                            >
                                                <i class="ti ti-eye"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            {/each}
                        </tbody>
                    </table>
                </div>
            {:else}
                <EmptyState height="250px" />
            {/if}
        {:else}
            <Loader height="250px" />
        {/if}
    </div>

    {#if patients.length > 0}
        <div class="card-footer border-0" style="background: var(--bs-body-bg);">
            <Pagination
                {pagination}
                on:update={(e) => {
                    pagination.current_page = e.detail.page;
                    handleGetPatients(e.detail.page);
                }}
            />
        </div>
    {/if}
</div>
