<script lang="ts">
    import { spaLink } from "../../actions"
    import { newNotification } from "../../store"
    import { cryptchaSolutionId, initCryptcha, cryptchaSolution } from "../../utils"
    import { apiBaseURL } from "../../../config"

    export let email = ""
    export let name = ""
    export let description = ""
    export let title = "Es sind noch Fragen offen?"

    let contactRequestSent = false
    let submitting = false
    let cryptchaEl: HTMLDivElement
    let cryptchaInitialized = false

    const contactRequest = {
        email,
        name,
        description,
        usageTerms: false,
    }

    const emailPattern = /^(?:[a-zA-Z0-9_'^&%+\-])+(?:\.(?:[a-zA-Z0-9_'^&%+\-])+)*@(?:(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|\[(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\]$/

    const validate = () => {
        if (!emailPattern.test(contactRequest.email || "")) {
            newNotification({ class: "error", html: "Bitte gib eine gültige E-Mail-Adresse an." })
            return false
        }

        if (!contactRequest.name?.trim()) {
            newNotification({ class: "error", html: "Bitte gib deinen Namen an." })
            return false
        }

        if (!contactRequest.description?.trim()) {
            newNotification({ class: "error", html: "Bitte beschreibe dein Anliegen." })
            return false
        }

        if (!contactRequest.usageTerms) {
            newNotification({ class: "error", html: "Bitte akzeptiere die Datenschutzerklärung." })
            return false
        }

        if (!$cryptchaSolution || !$cryptchaSolutionId) {
            newNotification({ class: "error", html: "Bitte löse die Sicherheitsabfrage." })
            return false
        }

        return true
    }

    const updateField = (field: keyof typeof contactRequest) => (event: Event) => {
        const target = event.currentTarget as HTMLInputElement | HTMLTextAreaElement
        if (field === "usageTerms") {
            contactRequest[field] = (target as HTMLInputElement).checked as never
        } else {
            contactRequest[field] = target.value as never
        }
    }

    $: if (cryptchaEl && !cryptchaInitialized && contactRequest.name && contactRequest.email) {
        initCryptcha(cryptchaEl)
        cryptchaInitialized = true
    }

    const submitContactRequest = async () => {
        if (!validate() || submitting) return

        submitting = true
        try {
            const response = await fetch(`${apiBaseURL}support-requests`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Accept: "application/json",
                },
                body: JSON.stringify({
                    ...contactRequest,
                    solution: $cryptchaSolution,
                    solutionId: $cryptchaSolutionId,
                }),
            })

            if (!response.ok) {
                throw new Error(`Request failed with status ${response.status}`)
            }

            newNotification({ class: "success", html: "Deine Anfrage wurde erfolgreich versendet!" })
            contactRequestSent = true
        } catch (error) {
            console.error("Failed to submit contact request", error)
            newNotification({
                class: "error",
                html: "Die Anfrage konnte nicht gesendet werden. Bitte versuche es später erneut.",
            })
        } finally {
            submitting = false
        }
    }
</script>

<section class="small-wrapper contact">
    <div class="inner-small-wrapper">
        <div class="leftern">
            <small>Kundenservice</small>
            <h2>{title}</h2>
            <p>
                Konnte unser <a href="/helpCenter" use:spaLink>FAQ</a> dir nicht weiterhelfen? Kein Problem! Kontaktiere uns direkt, und unser Kundenservice steht dir gerne zur Verfügung.
            </p>
        </div>

        <form class="contactForm" on:submit|preventDefault|stopPropagation={submitContactRequest}>
            {#if contactRequestSent}
                <section class="row">
                    <p>Danke! Wir melden uns innerhalb der nächsten Werktage bei dir.</p>
                </section>
            {:else}
                <section class="row">
                    <label for="support-email">E-Mail</label>
                    <input
                        id="support-email"
                        type="email"
                        value={contactRequest.email}
                        on:input={updateField("email")}
                        required
                    />
                </section>
                <section class="row">
                    <label for="support-name">Name</label>
                    <input
                        id="support-name"
                        type="text"
                        value={contactRequest.name}
                        on:input={updateField("name")}
                        required
                    />
                </section>
                <section class="row">
                    <label for="support-description">Beschreibung</label>
                    <textarea
                        id="support-description"
                        rows={4}
                        value={contactRequest.description}
                        on:input={updateField("description")}
                        required
                    ></textarea>
                </section>
                <section class="row checkbox-row">
                    <input
                        id="support-usageTerms"
                        type="checkbox"
                        checked={contactRequest.usageTerms}
                        on:change={updateField("usageTerms")}
                        required
                    />
                    <p>
                        Ich habe die <a use:spaLink href="/datenschutz">Datenschutzerklärung</a> gelesen und akzeptiere sie.
                    </p>
                </section>
                <section class="row">
                    <button class="cta primary" type="submit" disabled={submitting}>
                        {submitting ? "Wird gesendet…" : "Absenden"}
                    </button>
                </section>
                <section class="row">
                    <div bind:this={cryptchaEl}></div>
                </section>
            {/if}
        </form>
    </div>
</section>

<style lang="less">
    @import "../../assets/css/variables.less";

    .small-wrapper.contact {
        display: flex;
        width: 100%;
    }

    .inner-small-wrapper {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 2.4rem;
        width: 100%;
    }

    .leftern {
        display: flex;
        flex-direction: column;
        gap: 0.6rem;
    }

    form {
        display: flex;
        flex-direction: column;
        gap: 0.8rem;
    }

    .row {
        display: flex;
        flex-direction: column;
        gap: 0.4rem;
    }

    .checkbox-row {
        flex-direction: row;
        align-items: flex-start;
        gap: 1rem;

        input {
            margin-top: 0.3rem;
        }

        p {
            margin: 0;
        }
    }

    input,
    textarea {
        padding: 0.6rem 0.8rem;
        border: 1px solid rgba(0, 0, 0, 0.15);
        border-radius: 6px;
        font: inherit;
    }
</style>
