<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { api_host } from '$lib';
	import type { Appointment, AppointmentDateTimes, AppointmentInputs, DynamicJson } from '$lib/dbdata';
	import AppointmentConfirmDialog from '$lib/modules/AppointmentConfirmDialog.svelte';
    import AppointmentInfo from '$lib/modules/AppointmentInfo.svelte';
    import DatePicker from '$lib/modules/DatePicker.svelte';
	import DateTimes from '$lib/modules/DateTimes.svelte';
	import { onMount } from 'svelte';

    let title: string = "Appointment";
    let location: string = "Somewhere";
    let description: string = "Description ...";

    let selectedDate: Date = new Date();
    let activateModal: boolean = false;
    let dynamicInputs: DynamicJson[] = [];
    let appointmentDateTimes: AppointmentDateTimes[] = [

    ];

    async function getAppointmentInfo(appointmentId: string) {
        const response = await fetch(`${api_host}/api/schedule?appointmentId=${appointmentId}`, {
                method: "GET",
                headers: {
                    "Content-Type": "application/json"
                }
            })
        const js: Appointment = await response.json();
        appointmentDateTimes = js.times.filter(element => element.available === false);
        title = js.title;
        description = js.description;
        location = js.place;
        dynamicInputs = js.inputs;

        if (response.status === 404) {
            goto('/errors/404');
        }
        if (response.status === 410) {
            goto('/errors/410');
        }
    }

    onMount(async () => {

        const id = $page.url.searchParams.get('id');
        if (!id) {
            goto('/errors/404');
        } else {
            await getAppointmentInfo(id);    
        }
    });

</script>
  
<style>
    .w-80 {
        max-width: 600px;
    }

    .inline-margin {
        margin-inline: auto;
    }
</style>

<DatePicker bind:appointmentDateTimes bind:selectedDate />

<div class="top-margin w-80 inline-margin"> 
    <AppointmentInfo bind:title bind:description bind:location />
    {#key selectedDate}
        <DateTimes bind:activateModal bind:selectedDate bind:availableTimes={appointmentDateTimes} />    
    {/key}
</div>

<AppointmentConfirmDialog bind:dynamicInputs bind:active={activateModal} bind:date={selectedDate} bind:title bind:description bind:location />