"use client";

import { useState, type FormEvent } from "react";
import { CheckIcon } from "./icons";

type Status = "idle" | "submitting" | "success" | "error";

const budgets = [
  "Under $10,000",
  "$10,000 – $25,000",
  "$25,000 – $50,000",
  "$50,000 – $100,000",
  "$100,000+",
  "Not sure yet",
];

const timelines = [
  "ASAP",
  "1–3 months",
  "3–6 months",
  "6–12 months",
  "Just exploring",
];

export function ContactForm({
  serviceOptions,
}: {
  serviceOptions: string[];
}) {
  const [status, setStatus] = useState<Status>("idle");
  const [error, setError] = useState<string>("");

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setStatus("submitting");
    setError("");

    const form = e.currentTarget;
    const data = Object.fromEntries(new FormData(form).entries());

    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!res.ok) {
        const body = (await res.json().catch(() => null)) as { error?: string } | null;
        throw new Error(body?.error ?? "Something went wrong. Please try again.");
      }
      setStatus("success");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong.");
      setStatus("error");
    }
  }

  if (status === "success") {
    return (
      <div className="card-soft p-10 text-center">
        <span className="mx-auto flex h-14 w-14 items-center justify-center rounded-full border border-teal text-teal">
          <CheckIcon className="h-6 w-6" />
        </span>
        <h3 className="display-3 mt-4">Thank you — we&apos;ve got it.</h3>
        <p className="mx-auto mt-3 max-w-sm text-ink-soft">
          We&apos;ll reply within one business day with a few times for your free
          discovery call. Keep an eye on your inbox.
        </p>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} noValidate={false}>
      <div className="grid gap-7 sm:grid-cols-2">
        <div>
          <label htmlFor="name" className="field-label">Full name *</label>
          <input id="name" name="name" type="text" required placeholder="Jane Doe" className="field-input" />
        </div>
        <div>
          <label htmlFor="email" className="field-label">Email *</label>
          <input id="email" name="email" type="email" required placeholder="jane@example.com" className="field-input" />
        </div>
        <div>
          <label htmlFor="phone" className="field-label">Phone (optional)</label>
          <input id="phone" name="phone" type="tel" placeholder="+1 555 000 0000" className="field-input" />
        </div>
        <div>
          <label htmlFor="service" className="field-label">I&apos;m interested in *</label>
          <select id="service" name="service" required defaultValue="" className="field-select">
            <option value="" disabled>
              Choose a service…
            </option>
            {serviceOptions.map((title) => (
              <option key={title} value={title}>
                {title}
              </option>
            ))}
            <option value="Not sure yet">Not sure yet</option>
          </select>
        </div>
        <div>
          <label htmlFor="budget" className="field-label">Budget *</label>
          <select id="budget" name="budget" required defaultValue="" className="field-select">
            <option value="" disabled>
              Select a range…
            </option>
            {budgets.map((b) => (
              <option key={b} value={b}>{b}</option>
            ))}
          </select>
        </div>
        <div>
          <label htmlFor="timeline" className="field-label">Timeline *</label>
          <select id="timeline" name="timeline" required defaultValue="" className="field-select">
            <option value="" disabled>
              When would you like to start?
            </option>
            {timelines.map((t) => (
              <option key={t} value={t}>{t}</option>
            ))}
          </select>
        </div>
        <div className="sm:col-span-2">
          <label htmlFor="message" className="field-label">About your project *</label>
          <textarea
            id="message"
            name="message"
            required
            rows={5}
            minLength={10}
            placeholder="Tell us about your space, how you live in it, and what's not working…"
            className="field-textarea resize-y"
          />
        </div>
      </div>

      {status === "error" ? (
        <p role="alert" className="mt-6 rounded-xl border border-coral/40 bg-coral-soft px-4 py-3 text-[0.9rem] text-coral-dark">
          {error}
        </p>
      ) : null}

      <button
        type="submit"
        disabled={status === "submitting"}
        className="btn btn-primary mt-9 w-full sm:w-auto disabled:cursor-not-allowed disabled:opacity-60"
      >
        {status === "submitting" ? "Sending…" : "Request my discovery call"}
      </button>
      <p className="mt-4 text-[0.8rem] text-ink-mute">
        We reply within one business day. No newsletters, no spam — just a
        human response.
      </p>
    </form>
  );
}
