"use client";

import BrandName from "@/app/BrandName";
import {
  FieldGrid,
  FieldGroup,
  FieldLabel,
  PrimaryButton,
  SelectField,
  TextareaField,
  TextField,
} from "@/app/FormFields";
import { useState } from "react";

const LINKEDIN_URL = "https://www.linkedin.com/company/quality-intelligence";
const CONTACT_EMAIL = "james@quality-intelligence.co";

export default function ContactPage() {
  const [form, setForm] = useState({
    name: "",
    email: "",
    company: "",
    role: "",
    industry: "",
    message: "",
  });
  const [status, setStatus] = useState<"idle" | "sending" | "sent" | "error">(
    "idle",
  );

  function set(key: keyof typeof form, value: string) {
    setForm((f) => ({ ...f, [key]: value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setStatus("sending");
    // www is the canonical domain; posting there avoids the apex→www 307 redirect that
    // breaks CORS preflights (browsers refuse to follow 307 on OPTIONS requests).
    const base =
      process.env.NODE_ENV === "production"
        ? "https://www.quality-intelligence.co"
        : "";
    try {
      const res = await fetch(`${base}/api/contact`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      setStatus(res.ok ? "sent" : "error");
    } catch {
      setStatus("error");
    }
  }

  return (
    <div className="bg-white dark:bg-zinc-950 text-zinc-950 dark:text-zinc-100">
      {/* Header */}
      <section className="mx-auto max-w-3xl px-6 pt-16 pb-12">
        <h1 className="text-4xl font-bold tracking-tight text-zinc-950 dark:text-white">
          Get in touch
        </h1>
        <p className="mt-5 text-lg text-zinc-600 dark:text-zinc-400 leading-relaxed">
          We are working with a small number of manufacturing teams in early
          access. If you would like to learn more, request a walkthrough, or
          just ask a question — send us a message and we will respond within one
          business day.
        </p>
      </section>

      <section className="border-t border-zinc-100 dark:border-zinc-800">
        <div className="mx-auto max-w-3xl px-6 py-14 grid gap-14 sm:grid-cols-5">
          {/* Form */}
          <div className="sm:col-span-3">
            {status === "sent" ? (
              <div className="rounded-xl border border-green-200 bg-green-50 p-8 dark:border-green-400/30 dark:bg-green-400/10 text-center">
                <p className="text-2xl mb-3">✓</p>
                <h2 className="font-semibold text-green-900 dark:text-green-200 mb-2">
                  Message received
                </h2>
                <p className="text-sm text-green-800 dark:text-green-300">
                  Thanks for reaching out. We will be in touch within one
                  business day.
                </p>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-5">
                <FieldGrid className="gap-5">
                  <FieldGroup>
                    <FieldLabel required>Your name</FieldLabel>
                    <TextField
                      type="text"
                      required
                      value={form.name}
                      onChange={(e) => set("name", e.target.value)}
                      placeholder="Jane Smith"
                    />
                  </FieldGroup>
                  <FieldGroup>
                    <FieldLabel required>Work email</FieldLabel>
                    <TextField
                      type="email"
                      required
                      value={form.email}
                      onChange={(e) => set("email", e.target.value)}
                      placeholder="jane@company.com"
                    />
                  </FieldGroup>
                </FieldGrid>
                <FieldGrid className="gap-5">
                  <FieldGroup>
                    <FieldLabel>Company</FieldLabel>
                    <TextField
                      type="text"
                      value={form.company}
                      onChange={(e) => set("company", e.target.value)}
                      placeholder="Acme Pharma Ltd"
                    />
                  </FieldGroup>
                  <FieldGroup>
                    <FieldLabel>Your role</FieldLabel>
                    <TextField
                      type="text"
                      value={form.role}
                      onChange={(e) => set("role", e.target.value)}
                      placeholder="Quality Director"
                    />
                  </FieldGroup>
                </FieldGrid>
                <FieldGroup>
                  <FieldLabel>Industry</FieldLabel>
                  <SelectField
                    value={form.industry}
                    onChange={(e) => set("industry", e.target.value)}
                    placeholderValue=""
                  >
                    <option value="">Select your industry…</option>
                    <option>Pharmaceutical & Biotech</option>
                    <option>Medical Devices</option>
                    <option>Food & Beverage</option>
                    <option>Industrial / Automotive</option>
                    <option>Other regulated manufacturing</option>
                  </SelectField>
                </FieldGroup>
                <FieldGroup>
                  <FieldLabel>What would you like to discuss?</FieldLabel>
                  <TextareaField
                    rows={4}
                    value={form.message}
                    onChange={(e) => set("message", e.target.value)}
                    placeholder="Tell us a bit about your team, the challenges you are facing, or what you'd like to see in a walkthrough…"
                  />
                </FieldGroup>

                {status === "error" && (
                  <p className="text-sm text-red-600 dark:text-red-400">
                    Something went wrong. Please email us directly at{" "}
                    <a href={`mailto:${CONTACT_EMAIL}`} className="underline">
                      {CONTACT_EMAIL}
                    </a>
                    .
                  </p>
                )}

                <PrimaryButton
                  type="submit"
                  loading={status === "sending"}
                >
                  {status === "sending" ? "Sending…" : "Send message"}
                </PrimaryButton>
              </form>
            )}
          </div>

          {/* Sidebar */}
          <aside className="sm:col-span-2 space-y-8">
            <div>
              <h3 className="text-sm font-semibold text-zinc-950 dark:text-white mb-3">
                Follow us
              </h3>
              <a
                href={LINKEDIN_URL}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-2 text-sm text-zinc-600 hover:text-zinc-950 dark:text-zinc-400 dark:hover:text-white transition"
              >
                <LinkedInIcon className="h-4 w-4" />
                Quality Intelligence on LinkedIn
              </a>
            </div>

            <div className="rounded-lg border border-zinc-200 bg-zinc-50 p-4 dark:border-zinc-800 dark:bg-zinc-900 space-y-2">
              <p className="text-xs font-semibold text-zinc-500 dark:text-zinc-400 uppercase tracking-wide">
                What to expect
              </p>
              <ul className="space-y-1.5 text-sm text-zinc-600 dark:text-zinc-400">
                <li>→ Reply within one business day</li>
                <li>→ No sales pressure or generic demos</li>
                <li>
                  → A genuine conversation about whether <BrandName /> fits
                  your team
                </li>
                <li>
                  → If it does, a live walkthrough using your industry scenarios
                </li>
              </ul>
            </div>
          </aside>
        </div>
      </section>
    </div>
  );
}

function LinkedInIcon({ className }: { className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 24 24"
      fill="currentColor"
      aria-hidden="true"
    >
      <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
    </svg>
  );
}
