<script lang="ts">
    import { writable } from "svelte/store"
    import { validateFields } from "../../../functions/pagebuilder/components/form/validateFields"
    import { sendForm } from "../../../functions/pagebuilder/components/form/sendForm"

    import { modules } from "../../../store"
    import FormColumnWrapper from "./FormColumnWrapper.svelte"
    import { navigateWrapper } from "../../../functions/utils"

    export let col: { contentType: "form"; moduleImport: string }

    export let pageId: string
    // @ts-ignore
    let form: DBFormObj = $modules[col?.moduleImport]?.form
    $: form = $modules[col?.moduleImport]?.form
    let formSend = false
    let formValues = writable<FormValues>({})

    function submitForm() {
        const values: Array<ValueEntry> = Object.entries($formValues).map((entry: ObjectEntry) => {
            const key: string = entry[0]
            const value: CustomHTMLElement = entry[1]

            if (!key.includes("numberLabel")) {
                return [key, [value.type == "checkbox" ? value.checked : value.value, value.required]] as ValueEntry
            } else {
                return [key, [value.value, value, value.getAttribute("name"), value.required]] as ValueEntry
            }
        })

        const fields: Array<ValueEntry> = values.filter((entry: ValueEntry) => !entry[0].includes("label"))
        const validation = validateFields(fields)
        if (validation.length) {
            validation.forEach((error: string[]) => {
                // @ts-ignore
                if (error[0].includes("block")) {
                    // @ts-ignore
                    error[1]()
                } else {
                    // @ts-ignore
                    $formValues[error[1]].classList.add("invalid")
                    const label = $formValues[`${error[1]}_label`]
                    const errorElement = document.createElement("div")
                    errorElement.className = "error-message"
                    errorElement.textContent = error[0] as string
                    label?.appendChild(errorElement)
                }
            })
        } else {
            // @ts-ignore
            const formObj: FormObj = {}
            fields.forEach((entry) => {
                if (Array.isArray(entry[1]) && entry[1].length == 4) {
                    // @ts-ignore
                    if (entry[1][0]) formObj[entry[0]] = entry[1]
                } else {
                    if (!entry[1][0] && !entry[1][1]) return
                    // @ts-ignore
                    formObj[entry[0]] = entry[1][0]
                }
            })
            if (!form) {
                return
            }
            formObj["formRows"] = form.rows.map((r) => r.emailTitle)
            formObj["formTitle"] = form.emailSubject
            formSend = true
            const hny = document.getElementById("hny") as HTMLInputElement
            if (hny) formObj["honey"] = hny.checked
            sendForm(formObj)
        }
    }
</script>

<div class="my-form">
    {#if formSend}
        <div class="success-message">
            <h1>Formular erfolgreich gesendet!</h1>
            <p>Vielen Dank für Ihre Anfrage. Wir werden uns in Kürze bei Ihnen melden.</p>
        </div>
    {:else if form}
        <form
            class="form-rows"
            novalidate
            on:submit="{(e) => {
                e.preventDefault()
                submitForm()
            }}"
        >
            {#each form.rows ?? [] as formRow, i}
                <FormColumnWrapper {formRow} {formValues} index="{i}" />
            {/each}
            <div class="row additional" style="padding: 0px;">
                <input
                    type="checkbox"
                    name="contact_me_by_fax_only"
                    id="hny"
                    value="1"
                    style="position: absolute; left: -9999px;"
                    autocomplete="off"
                />
                <div class="data-protection">
                    <label bind:this="{$formValues[`agreement_label`]}">
                        <input
                            class="checkit"
                            required
                            type="checkbox"
                            on:change="{(e) => {
                                let element = e.currentTarget
                                element.classList.remove('invalid')
                            }}"
                            bind:this="{$formValues['agreement']}"
                        />
                        <span class="checkit-span"></span>
                    </label>

                    <div class="datasec">
                        <button on:click|preventDefault="{() => navigateWrapper('/datenschutz')}" class="link">
                            Datenschutz
                        </button>
                        akzeptieren
                    </div>
                </div>

                <button class="submit-request" type="submit">{form.sendFormBtnText || "Formular absenden"}</button>
            </div>
        </form>
    {/if}
</div>

<style lang="less" global>
    @import "../../../assets/css/components/pagebuilder/form/form.less";
</style>
