import React, { useEffect, useState } from "react";
import { SiteHeader } from "@/components/SiteHeader";
import { SiteFooter } from "@/components/SiteFooter";
import { usePageMeta } from "@/lib/seo";

declare global {
    interface Window {
        turnstile?: { reset: () => void };
    }
}

const navigationItems = [
    { label: "Home", href: "/" },
    { label: "About", href: "/about" },
    { label: "News", href: "/events" },
    { label: "Support Us", href: "/support-us" },
    { label: "Contact", href: "/contact" },
];

export const Contact = (): JSX.Element => {
    const turnstileSiteKey = import.meta.env.VITE_TURNSTILE_SITE_KEY ?? "";
    const [formStatus, setFormStatus] = useState<
        "idle" | "sending" | "success" | "error"
    >("idle");
    const [formMessage, setFormMessage] = useState("");

    useEffect(() => {
        if (!turnstileSiteKey) {
            return;
        }
        const existingScript = document.querySelector("script[data-turnstile]");
        if (existingScript) {
            return;
        }
        const script = document.createElement("script");
        script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js";
        script.async = true;
        script.defer = true;
        script.dataset.turnstile = "true";
        document.body.appendChild(script);
    }, [turnstileSiteKey]);

    usePageMeta({
        title: "Contact",
        path: "/contact",
        description:
            "Contact Highland Group RDA for sessions, volunteering, and support.",
    });

    const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        if (formStatus === "sending") {
            return;
        }
        setFormStatus("sending");
        setFormMessage("");
        const form = event.currentTarget;
        const formData = new FormData(form);
        try {
            const response = await fetch(form.action, {
                method: "POST",
                body: formData,
            });
            if (!response.ok) {
                const errorData = (await response.json().catch(() => null)) as {
                    error?: string;
                    details?: string;
                } | null;
                if (errorData?.error) {
                    const detail = errorData.details
                        ? ` (${errorData.details})`
                        : "";
                    throw new Error(`${errorData.error}${detail}`);
                }
                const errorText = await response.text().catch(() => "");
                const message = errorText.trim()
                    ? `${response.status} ${response.statusText}: ${errorText}`
                    : `${response.status} ${response.statusText}`;
                throw new Error(message || "Request failed");
            }
            setFormStatus("success");
            setFormMessage("Thanks! Your message has been sent.");
            form.reset();
            if (window.turnstile?.reset) {
                window.turnstile.reset();
            }
        } catch (error) {
            setFormStatus("error");
            setFormMessage(
                error instanceof Error
                    ? error.message
                    : "Sorry, something went wrong. Please try again.",
            );
        }
    };
    return (
        <div className="flex flex-col min-h-screen items-center bg-[#e2e2e2]">
            <main className="w-full">
                <section className="w-full max-w-[1200px] mx-auto px-0 sm:px-8 mt-0">
                    <div
                        className="relative w-full sm:rounded-[7px] overflow-hidden bg-cover bg-[50%_35%]"
                        style={{
                            backgroundImage:
                                "url(/222957077_6028824210491349_4146132303877993139_n-1920w.webp)",
                        }}
                    >
                        <div className="absolute inset-0 bg-black/45" />
                        <SiteHeader
                            navigationItems={navigationItems}
                            theme="dark"
                            className="px-6 sm:px-4"
                        />
                        <div className="relative px-6 sm:px-8 pb-32 pt-6 sm:pb-24 sm:pt-8">
                            <div className="max-w-none sm:max-w-[760px] rounded-[7px] bg-black/45 px-5 py-5 sm:px-6 sm:py-6 backdrop-blur-sm">
                                <p className="[font-family:'Public_Sans',Helvetica] font-semibold text-xs sm:text-sm uppercase tracking-[0.2em] text-white/90">
                                    Get in touch
                                </p>
                                <div className="mt-3 h-[2px] w-10 bg-white/70" />
                                <h1 className="mt-4 [font-family:'Merriweather',Helvetica] font-bold text-white text-[34px] sm:text-[44px] leading-[1.15]">
                                    Contact Highland Group RDA
                                </h1>
                                <p className="mt-4 [font-family:'Public_Sans',Helvetica] font-semibold text-white text-base sm:text-lg leading-[1.6] max-w-[720px]">
                                    We would love to hear from you about
                                    sessions, volunteering, or ways to support
                                    the group. Reach out and we will get back to
                                    you as soon as we can.
                                </p>
                            </div>
                        </div>
                        <a
                            className="absolute bottom-4 left-4 sm:bottom-6 sm:left-6 w-[190px] sm:w-[240px] h-[48px] sm:h-[50px]"
                            href="https://www.justgiving.com/charity/highlandgrouprda"
                            target="_blank"
                            rel="noreferrer"
                        >
                            <img
                                className="w-full h-full object-contain"
                                alt="Donate via JustGiving"
                                src="/Button.webp"
                            />
                        </a>
                    </div>
                </section>

                <section className="w-full max-w-[1200px] mx-auto px-0 sm:px-8 mt-0 pb-0">
                    <div className="bg-[#d6d6d6] px-6 sm:px-8 py-6 sm:py-8">
                        <div className="grid grid-cols-1 gap-8 sm:grid-cols-[1.1fr_0.9fr]">
                            <div>
                                <h2 className="[font-family:'Merriweather',Helvetica] font-bold text-black text-2xl sm:text-3xl">
                                    Contact details
                                </h2>
                                <p className="mt-4 [font-family:'Public_Sans',Helvetica] font-semibold text-black text-base sm:text-lg leading-[1.6]">
                                    Highland Group RDA, Sandycroft, Reelig,
                                    Kirkhill, IV5 7PP
                                </p>
                                <p className="mt-3 [font-family:'Public_Sans',Helvetica] font-semibold text-black text-base sm:text-lg leading-[1.6]">
                                    Tel: +447500 203226
                                    <br />
                                    Email: info@highlandgrouprda.org.uk
                                </p>
                                <div className="mt-6">
                                    <a
                                        className="inline-flex items-center rounded-full border border-black/20 px-4 py-2 text-sm font-semibold uppercase tracking-wide text-black"
                                        href="mailto:info@highlandgrouprda.org.uk"
                                    >
                                        Email us
                                    </a>
                                </div>
                            </div>

                            <div className="bg-white/70 px-6 sm:px-8 py-6 sm:py-8">
                                <h2 className="[font-family:'Merriweather',Helvetica] font-bold text-black text-2xl sm:text-3xl">
                                    Send a message
                                </h2>
                                <form
                                    className="mt-4 space-y-4"
                                    action="/api/contact"
                                    method="post"
                                    onSubmit={handleSubmit}
                                >
                                    <div>
                                        <label className="block text-sm font-semibold text-black">
                                            Name
                                        </label>
                                        <input
                                            className="mt-2 w-full rounded-md border border-black/20 bg-white px-3 py-2 text-black"
                                            type="text"
                                            name="name"
                                            autoComplete="name"
                                            required
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-semibold text-black">
                                            Email
                                        </label>
                                        <input
                                            className="mt-2 w-full rounded-md border border-black/20 bg-white px-3 py-2 text-black"
                                            type="email"
                                            name="email"
                                            autoComplete="email"
                                            required
                                        />
                                    </div>
                                    <div>
                                        <label className="block text-sm font-semibold text-black">
                                            Message
                                        </label>
                                        <textarea
                                            className="mt-2 w-full rounded-md border border-black/20 bg-white px-3 py-2 text-black"
                                            name="message"
                                            rows={4}
                                            required
                                        />
                                    </div>
                                    <div
                                        className="cf-turnstile"
                                        data-sitekey={turnstileSiteKey}
                                    />
                                    {formMessage ? (
                                        <p className="text-sm font-semibold text-black">
                                            {formMessage}
                                        </p>
                                    ) : null}
                                    <button
                                        className="inline-flex items-center rounded-full border border-black/20 px-5 py-2 text-sm font-semibold uppercase tracking-wide text-black"
                                        type="submit"
                                        disabled={formStatus === "sending"}
                                    >
                                        {formStatus === "sending"
                                            ? "Sending..."
                                            : "Send message"}
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                </section>
                <section className="w-full max-w-[1200px] mx-auto px-0 sm:px-8 mt-0 pb-0">
                    <div className="bg-[#d6d6d6] px-6 sm:px-8 py-6 sm:py-8">
                        <div className="h-px w-full bg-black/20 mb-6" />
                        <div className="overflow-hidden rounded-[7px] border border-black/10">
                            <iframe
                                title="Highland Group RDA location"
                                src="https://www.google.com/maps?q=IV5%207PP&z=11&output=embed"
                                className="w-full h-[300px] sm:h-[380px] border-0"
                                loading="lazy"
                                referrerPolicy="no-referrer-when-downgrade"
                            />
                        </div>
                    </div>
                </section>
                <SiteFooter fullBleedOnMobile />
            </main>
        </div>
    );
};
