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

    export let dynamicInputs: DynamicJson[] = [];

    let inputValues: Record<string, string> = {};
    let errorMessage: 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;
        }
    }

    // TODO: please send record to api
    function submit() {
        const jsonOutput: Record<string, any> = {};
        errorMessage = "";
        if (Object.keys(inputValues).length != dynamicInputs.length) {
            errorMessage = "Not all inputs filled";
        }
        for (const dInput of dynamicInputs) {
            if (inputValues[dInput.name]) {
                jsonOutput[dInput.name] = inputValues[dInput.name];
                if (!validateInput(jsonOutput[dInput.name], dInput.type)) {
                    errorMessage = "Invalid inputs";
                }
            }
        }
        console.log(jsonOutput); // Output the JSON object
    }

</script>

{#each dynamicInputs as dInput, index}
    <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}

{#if errorMessage}
    <p class="error-text">{errorMessage}</p>
{/if}

<button on:click={submit}>Submit</button>