"use client";

import { useState } from "react";

const DIVISIONS = [
  { value: "", label: "Not sure yet — help me figure it out" },
  { value: "systems", label: "dChimes Systems (website + booking + marketing)" },
  { value: "digital", label: "dChimes Digital (SEO / content)" },
  { value: "ai", label: "dChimes AI (automation)" },
  { value: "cloud", label: "dChimes Cloud (hosting / domains)" },
  { value: "media", label: "dChimes Media (content / creative)" },
];

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

export function BookingIntakeForm() {
  const [status, setStatus] = useState<Status>("idle");

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

    const form = new FormData(e.currentTarget);
    const payload = {
      name: form.get("name"),
      email: form.get("email"),
      phone: form.get("phone"),
      website: form.get("website"),
      challenge: form.get("challenge"),
      division: form.get("division"),
    };

    try {
      const res = await fetch("/api/book", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error("Request failed");
      setStatus("success");
    } catch {
      setStatus("error");
    }
  }

  if (status === "success") {
    return (
      <div className="rounded-card border border-navy/10 bg-gray-light p-8 text-center">
        <h3 className="mb-2 font-heading text-xl font-semibold">You&apos;re in.</h3>
        <p className="text-navy/65">
          Pick a time below and we&apos;ll take it from there — we&apos;ll take a
          look at what you shared before the call so we don&apos;t waste your
          30 minutes on the basics.
        </p>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5">
      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
        <Field label="Your name" name="name" required />
        <Field label="Email" name="email" type="email" required />
      </div>
      <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
        <Field label="Phone" name="phone" />
        <Field label="Your website (if you have one)" name="website" placeholder="yourbusiness.com" />
      </div>

      <label className="block">
        <span className="mb-1.5 block text-sm font-medium text-navy">
          What&apos;s the biggest thing slowing your business down right now?
        </span>
        <textarea
          name="challenge"
          rows={4}
          required
          className="w-full rounded-xl border border-navy/15 p-3.5 text-[15px] outline-none focus:border-blue"
          placeholder="e.g. we get enquiries but too many people never actually book"
        />
      </label>

      <label className="block">
        <span className="mb-1.5 block text-sm font-medium text-navy">
          What would you like us to focus on?
        </span>
        <select
          name="division"
          className="w-full rounded-xl border border-navy/15 bg-white p-3.5 text-[15px] outline-none focus:border-blue"
        >
          {DIVISIONS.map((d) => (
            <option key={d.value} value={d.value}>
              {d.label}
            </option>
          ))}
        </select>
      </label>

      <p className="text-xs text-navy/45">
        If you shared a website above, we&apos;ll take a quick automated look at
        it before the call so we can come prepared — not to sell you anything,
        just so we don&apos;t waste your 30 minutes on the obvious stuff.
      </p>

      <button
        type="submit"
        disabled={status === "submitting"}
        className="w-full rounded-full bg-green px-6 py-4 text-[15px] font-semibold text-white disabled:opacity-60 sm:w-auto"
      >
        {status === "submitting" ? "Sending…" : "Continue to book your time"}
      </button>

      {status === "error" && (
        <p className="text-sm text-red-600">
          Something went wrong sending that — mind trying again, or email us
          directly for now?
        </p>
      )}
    </form>
  );
}

function Field({
  label,
  name,
  type = "text",
  required = false,
  placeholder,
}: {
  label: string;
  name: string;
  type?: string;
  required?: boolean;
  placeholder?: string;
}) {
  return (
    <label className="block">
      <span className="mb-1.5 block text-sm font-medium text-navy">{label}</span>
      <input
        name={name}
        type={type}
        required={required}
        placeholder={placeholder}
        className="w-full rounded-xl border border-navy/15 p-3.5 text-[15px] outline-none focus:border-blue"
      />
    </label>
  );
}
