import { useState, type FormEvent } from "react";
import { createFileRoute } from "@tanstack/react-router";
import { PageIntro } from "@/components/site/layout";
import { FIRM } from "@/lib/content";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/contact")({
  component: ContactPage,
  head: () => ({
    meta: [{ title: "Contact — Daciora Consulting" }],
  }),
});

const SUBJECTS = [
  "Defence policy",
  "Defence industry",
  "Defence research",
  "Media & speaking",
  "Other",
] as const;

function ContactPage() {
  const [sent, setSent] = useState(false);
  const [error, setError] = useState("");
  const [mailto, setMailto] = useState(`mailto:${FIRM.email}`);

  function onSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setError("");
    const data = new FormData(event.currentTarget);
    const name = String(data.get("name") ?? "").trim();
    const org = String(data.get("organisation") ?? "").trim();
    const email = String(data.get("email") ?? "").trim();
    const subject = String(data.get("subject") ?? "").trim();
    const message = String(data.get("message") ?? "").trim();

    if (!name || !org || !email || !subject || !message) {
      setError("Please complete every field.");
      return;
    }
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setError("Please enter a valid email address.");
      return;
    }

    const body = [
      `Name: ${name}`,
      `Organisation: ${org}`,
      `Email: ${email}`,
      `Subject: ${subject}`,
      "",
      message,
    ].join("\n");

    const href = `mailto:${FIRM.email}?subject=${encodeURIComponent(
      `Enquiry — ${subject}`,
    )}&body=${encodeURIComponent(body)}`;
    setMailto(href);
    setSent(true);
  }

  return (
    <>
      <PageIntro
        kicker="Contact"
        title="Write to a principal."
        lede="Enquiries are reviewed in Singapore. We reply to serious correspondence. Please do not send classified or restricted material."
      />

      <section className="bg-paper text-ink-fg">
        <div className="site-wrap grid gap-14 py-16 md:grid-cols-12 md:py-24">
          <div className="md:col-span-5">
            <img
              src="/images/colonnade.jpg"
              alt="Evening colonnade in Singapore’s financial district."
              className="aspect-4/5 w-full object-cover"
            />
            <div className="mt-8 space-y-6">
              <div>
                <p className="label-kicker !text-ink-muted">Email</p>
                <a
                  href={`mailto:${FIRM.email}`}
                  className="mt-2 block font-display text-2xl text-ink-fg no-underline"
                >
                  {FIRM.email}
                </a>
              </div>
              <div>
                <p className="label-kicker !text-ink-muted">Telephone</p>
                <p className="mt-2 font-display text-2xl">{FIRM.phone}</p>
              </div>
              <div>
                <p className="label-kicker !text-ink-muted">Office</p>
                <address className="mt-2 not-italic font-display text-2xl leading-snug">
                  {FIRM.addressLines.map((line) => (
                    <span key={line} className="block">
                      {line}
                    </span>
                  ))}
                </address>
                <p className="mt-3 text-sm text-ink-muted">{FIRM.hours}</p>
              </div>
            </div>
          </div>

          <div className="md:col-span-7">
            {sent ? (
              <div className="border border-rule bg-ivory p-8 md:p-10">
                <p className="label-kicker !text-ink-muted">Received</p>
                <h2 className="mt-4 font-display text-3xl font-medium">
                  Your message is ready to send.
                </h2>
                <p className="mt-4 leading-relaxed text-ink-muted">
                  Write to{" "}
                  <a
                    href={mailto}
                    className="text-ink-fg underline underline-offset-4"
                  >
                    {FIRM.email}
                  </a>
                  . A principal will reply on unclassified terms. Do not attach
                  or describe classified or restricted material.
                </p>
                <a
                  href={mailto}
                  className="mt-8 inline-flex min-h-12 items-center bg-ink px-6 text-[0.78rem] font-semibold tracking-[0.16em] text-fg uppercase no-underline transition-[background-color,scale] duration-150 ease-out hover:bg-ink-soft active:scale-[0.96]"
                >
                  Open email draft
                </a>
              </div>
            ) : (
              <form onSubmit={onSubmit} className="space-y-6" noValidate>
                <Field label="Name" name="name" autoComplete="name" />
                <Field
                  label="Organisation"
                  name="organisation"
                  autoComplete="organization"
                />
                <Field
                  label="Email"
                  name="email"
                  type="email"
                  autoComplete="email"
                />
                <div>
                  <label htmlFor="subject" className="label-kicker !text-ink-muted">
                    Subject
                  </label>
                  <select
                    id="subject"
                    name="subject"
                    defaultValue=""
                    className="mt-2 min-h-12 w-full border border-rule bg-ivory px-3 text-[1.02rem] text-ink-fg outline-none transition-[border-color] duration-150 focus:border-ink"
                  >
                    <option value="" disabled>
                      Select a practice
                    </option>
                    {SUBJECTS.map((item) => (
                      <option key={item} value={item}>
                        {item}
                      </option>
                    ))}
                  </select>
                </div>
                <div>
                  <label htmlFor="message" className="label-kicker !text-ink-muted">
                    Message
                  </label>
                  <textarea
                    id="message"
                    name="message"
                    rows={7}
                    className="mt-2 w-full border border-rule bg-ivory px-3 py-3 text-[1.02rem] text-ink-fg outline-none transition-[border-color] duration-150 focus:border-ink"
                  />
                </div>
                {error ? (
                  <p className="text-sm text-ink-fg" role="alert">
                    {error}
                  </p>
                ) : null}
                <p className="text-sm leading-relaxed text-ink-muted">
                  By sending an enquiry you confirm that the contents are
                  unclassified. Daciora does not accept restricted or classified
                  material by email.
                </p>
                <button
                  type="submit"
                  className={cn(
                    "inline-flex min-h-12 items-center bg-ink px-8",
                    "text-[0.78rem] font-semibold tracking-[0.16em] text-fg uppercase",
                    "transition-[background-color,scale] duration-150 ease-out",
                    "hover:bg-ink-soft active:scale-[0.96]",
                  )}
                >
                  Send enquiry
                </button>
              </form>
            )}
          </div>
        </div>
      </section>
    </>
  );
}

function Field({
  label,
  name,
  type = "text",
  autoComplete,
}: {
  label: string;
  name: string;
  type?: string;
  autoComplete?: string;
}) {
  return (
    <div>
      <label htmlFor={name} className="label-kicker !text-ink-muted">
        {label}
      </label>
      <input
        id={name}
        name={name}
        type={type}
        autoComplete={autoComplete}
        className="mt-2 min-h-12 w-full border border-rule bg-ivory px-3 text-[1.02rem] text-ink-fg outline-none transition-[border-color] duration-150 focus:border-ink"
      />
    </div>
  );
}
