"use client";

import { useState } from "react";

const topics = [
  { value: "general", label: "General Inquiry" },
  { value: "honey-bees", label: "Honey Bees" },
  { value: "personal-training", label: "Personal Training" },
  { value: "sourdough", label: "Sourdough Breads" },
  { value: "farm-to-table", label: "Farm-to-Table" },
  { value: "recreation-apps", label: "Recreation Apps" },
  { value: "laser-engraving", label: "Laser Engraving" },
  { value: "3d-printing", label: "3D Printing" },
];

export function ContactForm() {
  const [formState, setFormState] = useState<"idle" | "submitting" | "success" | "error">("idle");
  const [formMessage, setFormMessage] = useState("");

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const raw = new FormData(e.target as HTMLFormElement);
    const data: Record<string, string> = {} as Record<string, string>;
    raw.forEach((v, k) => { data[k] = v as string; });

    // Honeypot check — bots fill these hidden fields
    if (data.honeybee_website || data.honeybee_company) {
      // Silent success — indistinguishable from real submission
      setFormState("success");
      setFormMessage("Message sent successfully!");
      return;
    }

    setFormState("submitting");

    try {
      const response = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });

      const result = await response.json();

      if (!result.ok) {
        setFormState("error");
        setFormMessage(result.error || "Something went wrong. Please try again.");
        return;
      }

      setFormState("success");
      setFormMessage("Message sent successfully! We will get back to you soon.");
      (e.target as HTMLFormElement).reset();
    } catch {
      setFormState("error");
      setFormMessage("Network error. Please try again.");
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {formMessage && (
        <div
          className={`rounded-lg p-4 text-sm ${
            formState === "error"
              ? "bg-red-50 text-red-700 dark:bg-red-900/20 dark:text-red-400"
              : "bg-green-50 text-green-700 dark:bg-green-900/20 dark:text-green-400"
          }`}
          role="alert"
        >
          {formMessage}
        </div>
      )}

      <div>
        <label htmlFor="name" className="mb-1 block text-sm font-medium">
          Name <span className="text-red-500">*</span>
        </label>
        <input
          id="name"
          name="name"
          type="text"
          className="input"
          placeholder="Your name"
          required
          minLength={2}
          maxLength={80}
        />
      </div>

      <div>
        <label htmlFor="email" className="mb-1 block text-sm font-medium">
          Email <span className="text-red-500">*</span>
        </label>
        <input
          id="email"
          name="email"
          type="email"
          className="input"
          placeholder="you@example.com"
          required
          maxLength={254}
        />
      </div>

      <div>
        <label htmlFor="topic" className="mb-1 block text-sm font-medium">
          Topic
        </label>
        <select id="topic" name="topic" className="input" defaultValue="general">
          {topics.map((t) => (
            <option key={t.value} value={t.value}>{t.label}</option>
          ))}
        </select>
      </div>

      <div>
        <label htmlFor="phone" className="mb-1 block text-sm font-medium">
          Phone (optional)
        </label>
        <input
          id="phone"
          name="phone"
          type="tel"
          className="input"
          placeholder="(555) 123-4567"
        />
      </div>

      <div>
        <label htmlFor="message" className="mb-1 block text-sm font-medium">
          Message <span className="text-red-500">*</span>
        </label>
        <textarea
          id="message"
          name="message"
          className="textarea"
          placeholder="How can we help?"
          required
          minLength={10}
          maxLength={5000}
        />
      </div>

      {/* Honeypot — hidden from users, filled by bots */}
      <div className="hidden">
        <label htmlFor="honeybee_website" className="sr-only">Website</label>
        <input id="honeybee_website" name="honeybee_website" tabIndex={-1} autoComplete="off" />
        <label htmlFor="honeybee_company" className="sr-only">Company</label>
        <input id="honeybee_company" name="honeybee_company" tabIndex={-1} autoComplete="off" />
      </div>

      <button
        type="submit"
        disabled={formState === "submitting"}
        className="btn-primary w-full"
      >
        {formState === "submitting" ? "Sending..." : "Send Message"}
      </button>
    </form>
  );
}
