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

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

    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) {
                errorMessage = "";
                successMessage = $t("common.sucess-booking");
                booked = true;
            } else {
                successMessage = "";
                errorMessage = $t("common.error-booking");
            }

            setTimeout(() => {
                successMessage = "";
                errorMessage = "";
            }, 7500);
        } catch (error) {
            console.log(error);
        }
    }

    async function submit() {
        let customInputs: DynamicJson[] = [];
        errorMessage = "";
        if (Object.keys(inputValues).length != dynamicInputs.length) {
            errorMessage = $t("common.error-parameters");
            return;
        }
        for (const dInput of dynamicInputs) {
            if (inputValues[dInput.name]) {
                if (!validateInput(inputValues[dInput.name], dInput.type)) {
                    errorMessage = $t("common.error-invalid-parameters");
                    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}>{$t("common.book")}</button>
    <button class="border" on:click={closeModal}>{$t("common.cancel")}</button>
</nav>