import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useRef, useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { z } from "zod";
import { toast } from "sonner";
import { Mail, Phone, MapPin } 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";

const SITE_KEY = import.meta.env.VITE_TURNSTILE_SITE_KEY as string | undefined;

export const Route = createFileRoute("/contact")({
  head: () => ({
    meta: [
      { title: "Start a Project — Gatavase Corporation" },
      {
        name: "description",
        content:
          "Talk to Gatavase Corporation about AI, web, mobile or enterprise projects. Offices in Kampala, Uganda and Doha, Qatar.",
      },
      { property: "og:title", content: "Start a Project — Gatavase Corporation" },
      {
        property: "og:description",
        content: "Talk to Gatavase about AI, web, mobile and enterprise projects.",
      },
      { property: "og:url", content: "/contact" },
    ],
    links: [{ rel: "canonical", href: "/contact" }],
    scripts: [
      {
        type: "application/ld+json",
        children: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "ContactPage",
          name: "Contact Gatavase Corporation",
          url: "/contact",
          mainEntity: {
            "@type": "Organization",
            name: "Gatavase Corporation",
            email: "gazmanadvancedtechnologies@gmail.com",
            telephone: ["+256773231138", "+97433201668"],
          },
        }),
      },
    ],
  }),
  component: ContactPage,
});

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(),
  message: z.string().trim().min(10, "Tell us a bit more about your project").max(2000),
});

function ContactPage() {
  const send = useServerFn(submitContact);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [pending, setPending] = useState(false);
  const mountedAt = useRef(Date.now());
  const captchaRef = useRef<HTMLDivElement>(null);
  const [captchaToken, setCaptchaToken] = useState("");

  useEffect(() => {
    if (!SITE_KEY || !captchaRef.current) return;
    const w = window as unknown as { turnstile?: { render: (el: Element, o: object) => void } };
    const render = () => {
      if (w.turnstile && captchaRef.current && !captchaRef.current.childElementCount) {
        w.turnstile.render(captchaRef.current, {
          sitekey: SITE_KEY,
          theme: "dark",
          callback: (token: string) => setCaptchaToken(token),
          "expired-callback": () => setCaptchaToken(""),
        });
      }
    };
    if (w.turnstile) {
      render();
      return;
    }
    const script = document.createElement("script");
    script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
    script.async = true;
    script.onload = render;
    document.head.appendChild(script);
  }, []);

  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;
    }

    setErrors({});
    setPending(true);
    try {
      const result = await send({
        data: {
          ...parsed.data,
          source: "website-contact",
          website: raw.website ?? "",
          elapsedMs: Date.now() - mountedAt.current,
          captchaToken,
        },
      });

      if (result.ok) {
        toast.success("Thank you — your message is on its way to our team.");
        form.reset();
        mountedAt.current = Date.now();
      } 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-[1.1fr_1fr]">
        <div>
          <p className="font-mono text-xs tracking-[0.2em] text-primary uppercase">
            Contact & Locations
          </p>
          <h1 className="mt-4 text-4xl font-bold md:text-5xl">Let's build something meaningful.</h1>
          <p className="mt-5 max-w-lg leading-relaxed text-muted-foreground">
            Gatavase Corporation operates across Uganda and Qatar, serving clients and communities
            with dedication and clarity.
          </p>

          <div className="mt-10 space-y-4">
            <InfoRow icon={MapPin} title="Kampala HQ" value="Muyenga-Bukasa, Plot 68, Uganda" />
            <InfoRow icon={MapPin} title="Doha" value="Abu Nakhla, Al Rayyan, Qatar" />
            <InfoRow icon={Phone} title="Telephone" value="+256 773 231138 · +974 3320 1668" />
            <InfoRow icon={Mail} title="Email" value="gazmanadvancedtechnologies@gmail.com" />
          </div>
        </div>

        <form onSubmit={onSubmit} className="panel relative h-fit space-y-5 p-8" noValidate>
          <div className="space-y-2">
            <Label htmlFor="name">Name</Label>
            <Input id="name" name="name" placeholder="Your full name" maxLength={100} />
            <FieldError message={errors.name} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="email">Email</Label>
            <Input
              id="email"
              name="email"
              type="email"
              placeholder="you@company.com"
              maxLength={255}
            />
            <FieldError message={errors.email} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="company">Organization (optional)</Label>
            <Input
              id="company"
              name="company"
              placeholder="Company, school or NGO"
              maxLength={120}
            />
          </div>
          <div className="space-y-2">
            <Label htmlFor="message">Project details</Label>
            <Textarea
              id="message"
              name="message"
              rows={5}
              placeholder="What would you like to build?"
              maxLength={2000}
            />
            <FieldError message={errors.message} />
          </div>

          {/* Honeypot — hidden from humans, irresistible to bots. */}
          <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>

          {SITE_KEY ? <div ref={captchaRef} className="min-h-[65px]" /> : null}

          <Button type="submit" size="lg" className="w-full" disabled={pending}>
            {pending ? "Sending…" : "Start a Project"}
          </Button>
          <p className="text-xs text-muted-foreground">
            Protected against automated abuse. We reply from gazmanadvancedtechnologies@gmail.com.
          </p>
        </form>
      </div>
    </section>
  );
}

function FieldError({ message }: { message?: string }) {
  if (!message) return null;
  return <p className="text-xs text-destructive">{message}</p>;
}

function InfoRow({
  icon: Icon,
  title,
  value,
}: {
  icon: React.ElementType;
  title: string;
  value: string;
}) {
  return (
    <div className="flex items-start gap-4">
      <span className="grid size-10 shrink-0 place-items-center rounded-lg bg-primary/12 text-primary">
        <Icon className="size-4" />
      </span>
      <div>
        <p className="text-sm font-semibold">{title}</p>
        <p className="text-sm break-all text-muted-foreground">{value}</p>
      </div>
    </div>
  );
}
