"use client";

import { useState, type FormEvent } from "react";
import { Icon } from "@/components/icons";
import { site } from "@/content/site";

const services = [
  "Recruitment",
  "Career Coaching & CV writing",
  "Immigration",
  "Background check",
  "Team Building",
  "Other",
];

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

const isEmail = (v: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);

function validate(payload: Record<string, string>) {
  const errors: Record<string, string> = {};
  if (!payload.firstName?.trim()) errors.firstName = "Please enter your first name.";
  if (!payload.email?.trim()) errors.email = "Please enter your email.";
  else if (!isEmail(payload.email.trim())) errors.email = "Please enter a valid email address.";
  if ((payload.message ?? "").trim().length < 10)
    errors.message = "Please give us a little more detail (10+ characters).";
  return errors;
}

const fieldClass =
  "w-full rounded-xl border border-ink-200 bg-white px-4 py-3 text-sm text-ink-900 shadow-sm outline-none transition-colors placeholder:text-ink-400 focus:border-brand-500 focus:ring-2 focus:ring-brand-200";

export function ContactForm({ defaultService }: { defaultService?: string }) {
  const [status, setStatus] = useState<Status>("idle");
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [serverError, setServerError] = useState<string | null>(null);

  async function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setStatus("submitting");
    setErrors({});
    setServerError(null);

    const form = event.currentTarget;
    const fd = new FormData(form);
    const payload = Object.fromEntries(fd.entries()) as Record<string, string>;

    // Honeypot — pretend success without sending anything.
    if (payload.company?.trim()) {
      setStatus("success");
      form.reset();
      return;
    }

    const found = validate(payload);
    if (Object.keys(found).length > 0) {
      setErrors(found);
      setStatus("error");
      return;
    }

    try {
      const res = await fetch(site.formEndpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          name: `${payload.firstName ?? ""} ${payload.lastName ?? ""}`.trim(),
          email: payload.email,
          phone: payload.phone || "Not provided",
          service: payload.service || "Not specified",
          message: payload.message,
          _subject: `Website enquiry — ${payload.service || "General"}`,
          _template: "table",
          _captcha: "false",
        }),
      });
      const json = await res.json().catch(() => ({}) as Record<string, unknown>);

      if (res.ok && (json.success === "true" || json.success === true)) {
        setStatus("success");
        form.reset();
        return;
      }
      setServerError(
        typeof json.message === "string"
          ? json.message
          : "Something went wrong. Please try again or email us directly.",
      );
      setStatus("error");
    } catch {
      setServerError(
        `We could not reach the form service. Please email us directly at ${site.contact.email}.`,
      );
      setStatus("error");
    }
  }

  if (status === "success") {
    return (
      <div className="rounded-2xl border border-brand-200 bg-brand-50 p-8 text-center">
        <span className="mx-auto grid h-12 w-12 place-items-center rounded-full bg-brand-600 text-white">
          <Icon name="check" className="h-6 w-6" />
        </span>
        <h3 className="mt-4 font-display text-xl font-bold text-ink-900">
          Thank you — message received
        </h3>
        <p className="mt-2 text-sm text-ink-600">
          A consultant will get back to you within one business day. For anything
          urgent, call {site.contact.phone}.
        </p>
        <button
          type="button"
          onClick={() => setStatus("idle")}
          className="mt-5 text-sm font-semibold text-brand-700 underline underline-offset-4"
        >
          Send another message
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={onSubmit} noValidate className="grid gap-4">
      <div className="grid gap-4 sm:grid-cols-2">
        <Field label="First name" name="firstName" required error={errors.firstName} />
        <Field label="Last name" name="lastName" />
      </div>
      <div className="grid gap-4 sm:grid-cols-2">
        <Field label="Phone number" name="phone" type="tel" inputMode="tel" />
        <Field label="Email" name="email" type="email" required error={errors.email} />
      </div>

      <label className="grid gap-1.5 text-sm">
        <span className="font-medium text-ink-800">Choose a service</span>
        <select
          name="service"
          defaultValue={defaultService ?? ""}
          className={fieldClass}
        >
          <option value="" disabled>
            Select an option
          </option>
          {services.map((s) => (
            <option key={s} value={s}>
              {s}
            </option>
          ))}
        </select>
      </label>

      <label className="grid gap-1.5 text-sm">
        <span className="font-medium text-ink-800">
          Message <span className="text-brand-600">*</span>
        </span>
        <textarea
          name="message"
          required
          rows={5}
          placeholder="Tell us a little about what you need…"
          className={fieldClass}
        />
        {errors.message && <span className="text-xs text-accent-600">{errors.message}</span>}
      </label>

      {/* Honeypot */}
      <input
        type="text"
        name="company"
        tabIndex={-1}
        autoComplete="off"
        aria-hidden="true"
        className="hidden"
      />

      {serverError && (
        <p className="rounded-lg bg-accent-100 px-4 py-3 text-sm text-accent-600">
          {serverError}
        </p>
      )}

      <button
        type="submit"
        disabled={status === "submitting"}
        className="mt-1 inline-flex items-center justify-center gap-2 rounded-full bg-brand-700 px-6 py-3.5 text-sm font-semibold text-white transition-colors hover:bg-brand-600 disabled:opacity-60"
      >
        {status === "submitting" ? "Sending…" : "Send message"}
        {status !== "submitting" && <Icon name="arrow-right" className="h-4 w-4" />}
      </button>
      <p className="text-xs text-ink-400">
        By submitting this form you agree to be contacted about your enquiry. We
        keep your details confidential.
      </p>
    </form>
  );
}

function Field({
  label,
  name,
  type = "text",
  required = false,
  error,
  inputMode,
}: {
  label: string;
  name: string;
  type?: string;
  required?: boolean;
  error?: string;
  inputMode?: "tel" | "email" | "text";
}) {
  return (
    <label className="grid gap-1.5 text-sm">
      <span className="font-medium text-ink-800">
        {label} {required && <span className="text-brand-600">*</span>}
      </span>
      <input
        type={type}
        name={name}
        required={required}
        inputMode={inputMode}
        className={fieldClass}
      />
      {error && <span className="text-xs text-accent-600">{error}</span>}
    </label>
  );
}
