<script lang="ts">
	import { goto } from "$app/navigation";
	import { page } from "$app/stores";
    import { api_host, authToken } from "$lib";
	import type { Appointment, AppointmentBooking } from "$lib/dbdata";
	import { extractDate, extractTime } from "$lib/funcs";
	import AppointmentInfo from "$lib/modules/AppointmentInfo.svelte";
	import { onMount } from "svelte";

    let bookingData: AppointmentBooking[] = [];
    let appointmentData: Appointment;
    let ready: boolean = false;

    async function fetchParticipants(appointmentId: string) {
        try {
            const response = await fetch(`${api_host}/api/users/bookings?appointmentId=${appointmentId}`, {
                method: "GET",
                headers: {
                    "Authorization": "Bearer " + $authToken
                },
            });

            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }

            const data: AppointmentBooking[] = await response.json();
            bookingData = data;
        } catch (error) {
            console.log('Error during fetch:', error);
        }
    }

    async function fetchAppointment(appointmentId: string) {
        try {
            const response = await fetch(`${api_host}/api/schedule?appointmentId=${appointmentId}&isUser=true`, {
                method: "GET",
                headers: {
                    "Authorization": "Bearer " + $authToken
                },
            });

            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }

            const data: Appointment = await response.json();
            appointmentData = data;
        } catch (error) {
            console.log('Error during fetch:', error);
        }
    }

    onMount(async () => {
        const id = $page.url.searchParams.get('id');
        if (!id) {
            goto('/user/bookings');
        } else {
            await fetchAppointment(id);
            await fetchParticipants(id);
        }
       ready = true;
    });
</script>

{#if appointmentData && ready}

    <AppointmentInfo title={appointmentData.title} location={appointmentData.place} description={`${appointmentData.duration} Min`} />

    <table class="border large-space large-text">
        <thead>
            <tr>
                <th class="min center-align">Datum</th>
                <th class="min center-align">Zeit</th>
                {#if appointmentData}
                    {#each appointmentData.inputs as input}
                        <th class="min center-align">{input.name}</th>
                    {/each}
                {/if}
            </tr>
        </thead>
        <tbody>
            {#each bookingData as data}
                <tr>
                    <td class="center-align">{extractDate(data.time)}</td>
                    <td class="center-align">{extractTime(data.time)}</td>
                    {#each data.inputs as input}
                        <td class="center-align">{input.value}</td>    
                    {/each}
                </tr>
            {/each}
        </tbody>
    </table>
{/if}