<script setup lang="ts">
import { ref } from "vue";
import Icon from "../Icon.vue";
import { siteConfig } from "../../config/site";

const firstName = ref("");
const lastName = ref("");
const email = ref("");
const company = ref("");
const service = ref("");
const budget = ref("");
const message = ref("");
const status = ref<"idle" | "sending" | "success" | "error">("idle");
const errorMessage = ref("");
let timeoutId: ReturnType<typeof setTimeout>;

const handleSubmit = async (e: Event) => {
    if (timeoutId) clearTimeout(timeoutId);
    status.value = "sending";
    errorMessage.value = "";

    try {
        const response = await fetch("/api/contact", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
                subject: `New Contact Form Message from ${firstName.value} ${lastName.value}`,
                message: `From: ${firstName.value} ${lastName.value}
Email: ${email.value}
Company: ${company.value || "Not specified"}
Service Needed: ${service.value || "Not specified"}
Budget: ${budget.value || "Not specified"}

Project Details:
${message.value}`,
            }),
        });

        const data = await response.json();

        if (!response.ok) {
            throw new Error(
                data.error || data.message || "Failed to send message",
            );
        }

        status.value = "success";
        firstName.value = "";
        lastName.value = "";
        email.value = "";
        company.value = "";
        service.value = "";
        budget.value = "";
        message.value = "";
        timeoutId = setTimeout(() => (status.value = "idle"), 2000);
    } catch (error) {
        status.value = "error";
        errorMessage.value =
            error instanceof Error ? error.message : "Failed to send message";
        console.error("Submission error:", error);
        timeoutId = setTimeout(() => (status.value = "idle"), 2000);
    }
};
</script>

<template>
    <div class="max-w-2xl mx-auto">
        <div class="card bg-base-100 border border-base-300/50 shadow-xl">
            <div class="card-body p-8 lg:p-10">
                <form class="space-y-6" @submit.prevent="handleSubmit">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <fieldset class="fieldset">
                            <legend
                                class="fieldset-legend text-sm font-semibold text-base-content"
                            >
                                {{ siteConfig.contact.form.firstName }}
                            </legend>
                            <input
                                type="text"
                                name="firstName"
                                class="input input-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                                required
                                v-model="firstName"
                                :disabled="status === 'sending'"
                                :placeholder="
                                    siteConfig.contact.form.placeholders
                                        .firstName
                                "
                            />
                        </fieldset>
                        <fieldset class="fieldset">
                            <legend
                                class="fieldset-legend text-sm font-semibold text-base-content"
                            >
                                {{ siteConfig.contact.form.lastName }}
                            </legend>
                            <input
                                type="text"
                                name="lastName"
                                class="input input-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                                required
                                v-model="lastName"
                                :disabled="status === 'sending'"
                                :placeholder="
                                    siteConfig.contact.form.placeholders
                                        .lastName
                                "
                            />
                        </fieldset>
                    </div>

                    <fieldset class="fieldset">
                        <legend
                            class="fieldset-legend text-sm font-semibold text-base-content"
                        >
                            {{ siteConfig.contact.form.email }}
                        </legend>
                        <input
                            type="email"
                            name="email"
                            class="input input-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                            required
                            v-model="email"
                            :disabled="status === 'sending'"
                            :placeholder="
                                siteConfig.contact.form.placeholders.email
                            "
                        />
                    </fieldset>

                    <fieldset class="fieldset">
                        <legend
                            class="fieldset-legend text-sm font-semibold text-base-content"
                        >
                            {{ siteConfig.contact.form.company }}
                        </legend>
                        <input
                            type="text"
                            name="company"
                            class="input input-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                            v-model="company"
                            :disabled="status === 'sending'"
                            :placeholder="
                                siteConfig.contact.form.placeholders.company
                            "
                        />
                    </fieldset>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <fieldset class="fieldset">
                            <legend
                                class="fieldset-legend text-sm font-semibold text-base-content"
                            >
                                {{ siteConfig.contact.form.service }}
                            </legend>
                            <select
                                name="service"
                                aria-label="Service Needed"
                                class="select select-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                                v-model="service"
                                :disabled="status === 'sending'"
                            >
                                <option value="">
                                    {{
                                        siteConfig.contact.form
                                            .selectPlaceholders.service
                                    }}
                                </option>
                                <option
                                    v-for="s in siteConfig.contact.form
                                        .services"
                                    :key="s.value"
                                    :value="s.value"
                                >
                                    {{ s.label }}
                                </option>
                            </select>
                        </fieldset>
                        <fieldset class="fieldset">
                            <legend
                                class="fieldset-legend text-sm font-semibold text-base-content"
                            >
                                {{ siteConfig.contact.form.budget }}
                            </legend>
                            <select
                                name="budget"
                                aria-label="Project Budget"
                                class="select select-bordered w-full bg-base-100 focus:border-primary focus:outline-primary"
                                v-model="budget"
                                :disabled="status === 'sending'"
                            >
                                <option value="">
                                    {{
                                        siteConfig.contact.form
                                            .selectPlaceholders.budget
                                    }}
                                </option>
                                <option
                                    v-for="b in siteConfig.contact.form.budgets"
                                    :key="b.value"
                                    :value="b.value"
                                >
                                    {{ b.label }}
                                </option>
                            </select>
                        </fieldset>
                    </div>

                    <fieldset class="fieldset">
                        <legend
                            class="fieldset-legend text-sm font-semibold text-base-content"
                        >
                            {{ siteConfig.contact.form.message }}
                        </legend>
                        <textarea
                            id="project-details"
                            name="message"
                            class="textarea textarea-bordered h-36 w-full resize-none bg-base-100 focus:border-primary focus:outline-primary"
                            :placeholder="
                                siteConfig.contact.form.placeholders.message
                            "
                            required
                            v-model="message"
                            :disabled="status === 'sending'"
                        />
                    </fieldset>

                    <button
                        type="submit"
                        class="btn btn-lg w-full shadow-lg transition-all duration-300"
                        :class="[
                            status === 'success'
                                ? 'btn-success text-white'
                                : status === 'error'
                                  ? 'btn-error text-white'
                                  : 'btn-primary',
                        ]"
                        :disabled="status === 'sending' || status === 'success'"
                    >
                        <template v-if="status === 'sending'">
                            <span
                                class="loading loading-spinner loading-sm"
                            ></span>
                            {{ siteConfig.contact.form.sending }}
                        </template>
                        <template v-else-if="status === 'success'">
                            <Icon name="check-circle" class="w-5 h-5" />
                            {{ siteConfig.contact.form.success }}
                        </template>
                        <template v-else-if="status === 'error'">
                            <Icon name="x-circle" class="w-5 h-5" />
                            {{ errorMessage || siteConfig.contact.form.error }}
                        </template>
                        <template v-else>
                            <Icon name="paper-airplane" class="w-5 h-5" />
                            {{ siteConfig.contact.form.submit }}
                        </template>
                    </button>
                </form>
            </div>
        </div>

        <div class="mt-10 text-center">
            <p class="text-base-content/60 mb-4">
                {{ siteConfig.contact.direct.text }}
            </p>
            <a
                :href="`mailto:${siteConfig.contact.direct.email}`"
                class="link font-medium inline-flex items-center gap-2 text-base-content hover:text-primary"
            >
                <Icon name="envelope" class="w-5 h-5" />
                {{ siteConfig.contact.direct.email }}
            </a>
        </div>
    </div>
</template>
