<script lang="ts">
	import { api_host } from "$lib";
	import type { AppointmentInputs, DynamicJson } from "$lib/dbdata";
    import validator from "validator";

    export let dynamicInputs: DynamicJson[] = [];
    export let appointmentId: string;
    export let date: Date;
    export let modalActive: boolean;

    export let errorMessage: string = "";
    export let successMessage: string = "";

    let inputValues: Record<string, string> = {};

    function validateInput(value: string, type: string): boolean  {
        switch (type) {
            case "email":
                return validator.isEmail(value);
        
            case "text":
                return !validator.isEmpty(value);

            case "tel":
                return validator.isMobilePhone(value);

            default:
                return false;
        }
    }

    async function confirmBooking(customInputs: DynamicJson[]) {
        try {
            const response = await fetch(`${api_host}/api/schedule/create`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({
                    appointmentId: appointmentId,
                    time: date,
                    inputs: customInputs
                })
            })

            if (response.status === 200) {
                successMessage = "successfully booked";
            } else {
                errorMessage = "invalid credentials";
            }
        } catch (error) {
            console.log(error);
        }
    }
    
    async function submit() {
        let customInputs: DynamicJson[] = [];
        errorMessage = "";
        if (Object.keys(inputValues).length != dynamicInputs.length) {
            errorMessage = "Not all inputs filled";
            return;
        }
        for (const dInput of dynamicInputs) {
            if (inputValues[dInput.name]) {
                if (!validateInput(inputValues[dInput.name], dInput.type)) {
                    errorMessage = "Invalid inputs";
                    return;
                }
                customInputs = [...customInputs, {name: dInput.name, value: inputValues[dInput.name]}];
            }
        }

        await confirmBooking(customInputs);
    }

    function closeModal() {
        modalActive = false;
    }

</script>

{#each dynamicInputs as dInput}
    <div class="field border">
        <input id={dInput.name} type={dInput.type} placeholder={dInput.name} bind:value={inputValues[dInput.name]}>
        <label for={dInput.name}>{dInput.name}</label>
    </div>
{/each}

<nav class="right-align">
    <button on:click={submit}>Submit</button>
    <button class="border" on:click={closeModal}>Close</button>
</nav>