import { createFileRoute, Link } from "@tanstack/react-router";
import { useRef, useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { z } from "zod";
import { toast } from "sonner";
import { CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { submitContact } from "@/lib/contact.functions";

export const Route = createFileRoute("/demo-request")({
  head: () => ({
    meta: [
      { title: "Request a Demo — Gatavase Corporation" },
      {
        name: "description",
        content:
          "Tell Gatavase Corporation about your project and request a live demo of our AI, web, mobile, blockchain or enterprise solutions.",
      },
      { property: "og:title", content: "Request a Demo — Gatavase Corporation" },
      {
        property: "og:description",
        content: "Share your project details and book a live demo with the Gatavase team.",
      },
      { property: "og:type", content: "website" },
      { property: "og:url", content: "/demo-request" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
    links: [{ rel: "canonical", href: "/demo-request" }],
  }),
  component: DemoRequestPage,
});

const PROJECT_TYPES = [
  "AI & Automation",
  "Web Platform",
  "Mobile App",
  "Blockchain",
  "Enterprise Software",
  "Networking & Infrastructure",
  "Training",
  "Other",
];

const BUDGETS = ["Under $5,000", "$5,000 – $20,000", "$20,000 – $50,000", "$50,000+", "Not sure yet"];
const TIMELINES = ["ASAP", "1–3 months", "3–6 months", "6+ months", "Exploring options"];

const schema = z.object({
  name: z.string().trim().min(1, "Please enter your name").max(100),
  email: z.string().trim().email("Enter a valid email address").max(255),
  company: z.string().trim().max(120).optional(),
  phone: z.string().trim().max(40).optional(),
  projectType: z.string().trim().min(1, "Choose a project type"),
  budget: z.string().trim().optional(),
  timeline: z.string().trim().optional(),
  preferredDate: z.string().trim().optional(),
  details: z.string().trim().min(10, "Tell us a bit more about what you need").max(2000),
});

function DemoRequestPage() {
  const send = useServerFn(submitContact);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [pending, setPending] = useState(false);
  const [done, setDone] = useState(false);
  const mountedAt = useRef(Date.now());

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const form = e.currentTarget;
    const raw = Object.fromEntries(new FormData(form)) as Record<string, string>;
    const parsed = schema.safeParse(raw);

    if (!parsed.success) {
      const next: Record<string, string> = {};
      for (const issue of parsed.error.issues) next[String(issue.path[0])] = issue.message;
      setErrors(next);
      return;
    }

    const d = parsed.data;
    const message = [
      `Project type: ${d.projectType}`,
      `Budget: ${d.budget || "—"}`,
      `Timeline: ${d.timeline || "—"}`,
      `Preferred demo date: ${d.preferredDate || "—"}`,
      `Phone: ${d.phone || "—"}`,
      "",
      d.details,
    ].join("\n");

    setErrors({});
    setPending(true);
    try {
      const result = await send({
        data: {
          name: d.name,
          email: d.email,
          company: d.company || "",
          message,
          source: "demo-request",
          website: raw.website ?? "",
          elapsedMs: Date.now() - mountedAt.current,
          captchaToken: "",
        },
      });

      if (result.ok) {
        setDone(true);
        form.reset();
        mountedAt.current = Date.now();
        toast.success("Demo request received — we'll be in touch shortly.");
      } else {
        toast.error(result.message);
      }
    } catch {
      toast.error("Something went wrong. Please email gazmanadvancedtechnologies@gmail.com.");
    } finally {
      setPending(false);
    }
  }

  return (
    <section className="hero-surface">
      <div className="mx-auto grid max-w-6xl gap-14 px-5 py-24 lg:grid-cols-[1fr_1.15fr]">
        <div>
          <p className="font-mono text-xs tracking-[0.2em] text-primary uppercase">Demo Request</p>
          <h1 className="mt-4 text-4xl font-bold md:text-5xl">Start a project with Gatavase.</h1>
          <p className="mt-5 max-w-lg leading-relaxed text-muted-foreground">
            Tell us what you want to build. Our engineers review every request and come back with a
            plain answer on scope, approach and what a working demo would look like.
          </p>
          <ul className="mt-8 space-y-3 text-sm text-muted-foreground">
            {[
              "A reply from a real engineer, usually within two working days",
              "A walkthrough of comparable systems we've delivered",
              "An honest view of scope, cost drivers and timeline",
            ].map((item) => (
              <li key={item} className="flex gap-3">
                <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-primary" />
                {item}
              </li>
            ))}
          </ul>
          <p className="mt-8 text-sm text-muted-foreground">
            Prefer a simple message?{" "}
            <Link to="/contact" className="text-primary hover:underline">
              Use the contact form
            </Link>
            .
          </p>
        </div>

        {done ? (
          <div className="panel h-fit p-10 text-center">
            <CheckCircle2 className="mx-auto size-10 text-primary" />
            <h2 className="mt-4 text-2xl font-semibold">Request received</h2>
            <p className="mt-3 text-sm text-muted-foreground">
              Thank you — your demo request is on its way to our team at
              gazmanadvancedtechnologies@gmail.com. We'll reply to the email address you provided.
            </p>
            <Button className="mt-6" onClick={() => setDone(false)}>
              Send another request
            </Button>
          </div>
        ) : (
          <form onSubmit={onSubmit} className="panel relative h-fit space-y-5 p-8" noValidate>
            <div className="grid gap-5 sm:grid-cols-2">
              <Field label="Name" error={errors.name}>
                <Input id="name" name="name" placeholder="Your full name" maxLength={100} />
              </Field>
              <Field label="Email" error={errors.email}>
                <Input
                  id="email"
                  name="email"
                  type="email"
                  placeholder="you@company.com"
                  maxLength={255}
                />
              </Field>
              <Field label="Organization (optional)">
                <Input id="company" name="company" placeholder="Company, school or NGO" maxLength={120} />
              </Field>
              <Field label="Phone (optional)">
                <Input id="phone" name="phone" placeholder="+256 …" maxLength={40} />
              </Field>
              <Field label="Project type" error={errors.projectType}>
                <select
                  id="projectType"
                  name="projectType"
                  defaultValue=""
                  className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                >
                  <option value="" disabled>
                    Select…
                  </option>
                  {PROJECT_TYPES.map((t) => (
                    <option key={t} value={t}>
                      {t}
                    </option>
                  ))}
                </select>
              </Field>
              <Field label="Budget range (optional)">
                <select
                  id="budget"
                  name="budget"
                  defaultValue=""
                  className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                >
                  <option value="">Select…</option>
                  {BUDGETS.map((b) => (
                    <option key={b} value={b}>
                      {b}
                    </option>
                  ))}
                </select>
              </Field>
              <Field label="Timeline (optional)">
                <select
                  id="timeline"
                  name="timeline"
                  defaultValue=""
                  className="h-9 w-full rounded-md border border-input bg-background px-3 text-sm"
                >
                  <option value="">Select…</option>
                  {TIMELINES.map((t) => (
                    <option key={t} value={t}>
                      {t}
                    </option>
                  ))}
                </select>
              </Field>
              <Field label="Preferred demo date (optional)">
                <Input id="preferredDate" name="preferredDate" type="date" />
              </Field>
            </div>

            <Field label="What would you like us to demo?" error={errors.details}>
              <Textarea
                id="details"
                name="details"
                rows={5}
                placeholder="Describe the problem, users and any systems it must work with."
                maxLength={2000}
              />
            </Field>

            {/* Honeypot */}
            <div aria-hidden="true" className="absolute -left-[9999px] h-0 w-0 overflow-hidden">
              <label htmlFor="website">Website</label>
              <input id="website" name="website" tabIndex={-1} autoComplete="off" />
            </div>

            <Button type="submit" size="lg" className="w-full" disabled={pending}>
              {pending ? "Sending…" : "Submit demo request"}
            </Button>
            <p className="text-xs text-muted-foreground">
              We reply from gazmanadvancedtechnologies@gmail.com. Your details are never shared.
            </p>
          </form>
        )}
      </div>
    </section>
  );
}

function Field({
  label,
  error,
  children,
}: {
  label: string;
  error?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="space-y-2">
      <Label>{label}</Label>
      {children}
      {error ? <p className="text-xs text-destructive">{error}</p> : null}
    </div>
  );
}
