"use client";

import { FormEvent, useState } from "react";

type Delivery = "webhook" | "mailto" | "ignored";

export function ContactForm({ email }: { email: string | null }) {
  const [name, setName] = useState("");
  const [address, setAddress] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [note, setNote] = useState<string | null>(null);
  const [pending, setPending] = useState(false);

  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (pending) return;
    setPending(true);
    setError(null);
    setNote(null);
    const form = event.currentTarget;
    const honeypot = new FormData(form).get("company_website");
    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { Accept: "application/json", "Content-Type": "application/json" },
        body: JSON.stringify({
          name,
          email: address,
          message,
          company_website: typeof honeypot === "string" ? honeypot : "",
        }),
      });
      const data = (await response.json()) as {
        success?: boolean;
        delivery?: Delivery;
        mailto?: string;
        error?: { message?: string };
      };
      if (!response.ok || !data.success) {
        setError(data.error?.message || "The message could not be sent.");
        return;
      }
      if (data.delivery === "mailto" && data.mailto) {
        setNote("Your email app will open with this message. Send it there to finish the request.");
        window.location.href = data.mailto;
        return;
      }
      if (data.delivery === "webhook") {
        setNote("Your message was sent.");
        setName("");
        setAddress("");
        setMessage("");
        return;
      }
      setNote("Thanks.");
    } catch {
      setError("The message could not be sent. Try again later.");
    } finally {
      setPending(false);
    }
  }

  return (
    <form className="contact-form" onSubmit={onSubmit} noValidate>
      <p className="form-intro">
        {email
          ? `You can also write directly to ${email}.`
          : "This inbox is connected only when the site operator adds a contact email or webhook. The form will say so if a message cannot be delivered."}
      </p>
      <label htmlFor="contact-name">Name</label>
      <input id="contact-name" className="text-input" value={name} onChange={(event) => setName(event.target.value)} autoComplete="name" required />
      <label htmlFor="contact-email">Email</label>
      <input id="contact-email" className="text-input" type="email" value={address} onChange={(event) => setAddress(event.target.value)} autoComplete="email" required />
      <label htmlFor="contact-message">Message</label>
      <textarea id="contact-message" className="text-input" value={message} onChange={(event) => setMessage(event.target.value)} rows={6} required />
      <div className="honeypot" aria-hidden="true">
        <label htmlFor="company-website">Company website</label>
        <input id="company-website" name="company_website" tabIndex={-1} autoComplete="off" />
      </div>
      {error ? <p className="notice notice-error" role="alert">{error}</p> : null}
      {note ? <p className="notice notice-ok" role="status">{note}</p> : null}
      <button type="submit" className="button button-primary" disabled={pending}>
        {pending ? "Sending…" : "Send message"}
      </button>
    </form>
  );
}
