"use client";

import { useRef, useState, type FormEvent } from "react";

export default function ContactForm() {
  const formRef = useRef<HTMLFormElement>(null);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [pending, setPending] = useState(false);

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError("");
    setMessage("");
    const form = new FormData(event.currentTarget);
    const name = String(form.get("name") ?? "").trim();
    const email = String(form.get("email") ?? "").trim();
    const subject = String(form.get("subject") ?? "").trim();
    const text = String(form.get("message") ?? "").trim();
    const privacyAccepted = form.get("privacyAccepted") === "on";

    if (!name || !email.includes("@") || !subject || text.length < 10 || !privacyAccepted) {
      setError("Bitte füllen Sie alle Pflichtfelder aus und bestätigen Sie die Datenschutz-Hinweise.");
      return;
    }

    setPending(true);
    try {
      const response = await fetch("/api/contact", { method: "POST", body: form });
      const result = await response.json() as { message?: string };
      if (!response.ok) throw new Error(result.message ?? "Nachricht konnte nicht gesendet werden.");
      formRef.current?.reset();
      setMessage(result.message ?? "Ihre Nachricht wurde vorbereitet.");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Nachricht konnte nicht gesendet werden. Bitte versuchen Sie es später erneut.");
    } finally {
      setPending(false);
    }
  }

  return (
    <form ref={formRef} className="form" onSubmit={submit} noValidate>
      <div className="field">
        <label htmlFor="name">Name</label>
        <input id="name" name="name" />
      </div>
      <div className="field">
        <label htmlFor="email">E-Mail</label>
        <input id="email" name="email" type="email" />
      </div>
      <div className="field">
        <label htmlFor="phone">Telefon</label>
        <input id="phone" name="phone" />
      </div>
      <div className="field">
        <label htmlFor="subject">Betreff</label>
        <input id="subject" name="subject" />
      </div>
      <div className="field">
        <label htmlFor="message">Nachricht</label>
        <textarea id="message" name="message" />
      </div>
      <label className="checkbox">
        <input type="checkbox" name="privacyAccepted" />
        <span>Ich stimme zu, dass meine Angaben zur Bearbeitung der Kontaktanfrage verarbeitet werden.</span>
      </label>
      {error && <p className="error">{error}</p>}
      {message && <p className="success">{message}</p>}
      <button className="button" type="submit" disabled={pending}>{pending ? "Wird gesendet..." : "Nachricht senden"}</button>
    </form>
  );
}
