"use client";

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

const fieldClass =
  "w-full rounded-2xl border border-anouma-taupe/30 bg-background px-5 py-3.5 text-base text-anouma-plum placeholder:text-anouma-plum/50 focus:border-anouma-mauve-dark focus:outline-none";

type ContactFormProps = {
  toEmail: string;
  subjectPrefix?: string;
  submitLabel?: string;
};

/**
 * Opens the visitor's email client with a pre-filled message. There is no
 * backend configured yet — swap this for a Server Action once a mail
 * provider is connected.
 */
export function ContactForm({
  toEmail,
  subjectPrefix = "Nachricht über anouma.org",
  submitLabel = "Nachricht senden",
}: ContactFormProps) {
  const [sent, setSent] = useState(false);

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const data = new FormData(e.currentTarget);
    const name = String(data.get("name") ?? "");
    const email = String(data.get("email") ?? "");
    const message = String(data.get("message") ?? "");

    const subject = encodeURIComponent(`${subjectPrefix} von ${name}`);
    const body = encodeURIComponent(`${message}\n\n— ${name} (${email})`);
    window.location.href = `mailto:${toEmail}?subject=${subject}&body=${body}`;
    setSent(true);
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div>
        <label htmlFor="name" className="mb-2 block text-sm font-medium text-anouma-plum">
          Name
        </label>
        <input id="name" name="name" type="text" required className={fieldClass} autoComplete="name" />
      </div>
      <div>
        <label htmlFor="email" className="mb-2 block text-sm font-medium text-anouma-plum">
          E-Mail
        </label>
        <input id="email" name="email" type="email" required className={fieldClass} autoComplete="email" />
      </div>
      <div>
        <label htmlFor="message" className="mb-2 block text-sm font-medium text-anouma-plum">
          Deine Nachricht
        </label>
        <textarea id="message" name="message" required rows={5} className={fieldClass} />
      </div>
      <button
        type="submit"
        className="inline-flex items-center justify-center rounded-full bg-anouma-mauve-dark px-7 py-3.5 text-sm font-medium tracking-wide text-white transition-colors duration-300 hover:bg-anouma-plum"
      >
        {submitLabel}
      </button>
      {sent && (
        <p className="text-sm text-anouma-olive" role="status">
          Dein E-Mail-Programm sollte sich jetzt geöffnet haben. Falls nicht, schreib gerne direkt an{" "}
          {toEmail}.
        </p>
      )}
    </form>
  );
}
