import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { z } from "zod";
import { Mail, Phone, MapPin, Send, CheckCircle2 } from "lucide-react";
import { Reveal } from "@/components/Reveal";

export const Route = createFileRoute("/contact")({
  head: () => ({
    meta: [
      { title: "Contact — SSG Edge Projects" },
      {
        name: "description",
        content:
          "Get in touch with SSG Edge Projects. Email info@ssgedge.co.za or call +27 81 330 8164 to request a quote.",
      },
      { property: "og:title", content: "Contact SSG Edge Projects" },
      {
        property: "og:description",
        content: "Call +27 81 330 8164 or email info@ssgedge.co.za to discuss your project.",
      },
    ],
  }),
  component: ContactPage,
});

const contactSchema = z.object({
  name: z.string().trim().min(2, "Please enter your name").max(100),
  email: z.string().trim().email("Please enter a valid email").max(255),
  phone: z.string().trim().min(7, "Please enter a valid phone").max(30),
  message: z.string().trim().min(10, "Please add a little more detail").max(1000),
});

type FormState = z.infer<typeof contactSchema>;
type FormErrors = Partial<Record<keyof FormState, string>>;

function ContactPage() {
  const [values, setValues] = useState<FormState>({ name: "", email: "", phone: "", message: "" });
  const [errors, setErrors] = useState<FormErrors>({});
  const [sent, setSent] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  function update<K extends keyof FormState>(k: K, v: string) {
    setValues((p) => ({ ...p, [k]: v }));
  }

  function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    const parsed = contactSchema.safeParse(values);
    if (!parsed.success) {
      const errs: FormErrors = {};
      for (const issue of parsed.error.issues) {
        const key = issue.path[0] as keyof FormState;
        if (!errs[key]) errs[key] = issue.message;
      }
      setErrors(errs);
      return;
    }
    setErrors({});
    setSubmitting(true);
    // Compose a mailto: as a graceful no-backend fallback
    const subject = encodeURIComponent(`Quote request from ${parsed.data.name}`);
    const body = encodeURIComponent(
      `Name: ${parsed.data.name}\nEmail: ${parsed.data.email}\nPhone: ${parsed.data.phone}\n\n${parsed.data.message}`,
    );
    window.location.href = `mailto:info@ssgedge.co.za?subject=${subject}&body=${body}`;
    setTimeout(() => {
      setSubmitting(false);
      setSent(true);
    }, 400);
  }

  return (
    <>
      <section className="relative isolate gradient-hero pt-32 pb-20 text-white md:pt-40 md:pb-28">
        <div className="container-edge">
          <Reveal>
            <span className="text-xs font-semibold uppercase tracking-[0.22em] text-primary-foreground/70">Contact</span>
          </Reveal>
          <Reveal delay={80}>
            <h1 className="mt-3 max-w-3xl text-4xl font-extrabold leading-tight tracking-tight sm:text-5xl md:text-6xl">
              Let's talk about your project.
            </h1>
          </Reveal>
          <Reveal delay={160}>
            <p className="mt-5 max-w-2xl text-primary-foreground/80">
              Send us a message and our team will get back to you with a clear, no-obligation proposal.
            </p>
          </Reveal>
        </div>
      </section>

      <section className="py-20 md:py-24">
        <div className="container-edge grid gap-10 lg:grid-cols-[1fr_1.3fr]">
          <Reveal>
            <div className="space-y-6">
              <ContactCard icon={Mail} title="Email" lines={[{ text: "info@ssgedge.co.za", href: "mailto:info@ssgedge.co.za" }]} />
              <ContactCard icon={Phone} title="Phone" lines={[{ text: "+27 81 330 8164", href: "tel:+27813308164" }]} />
              <ContactCard
                icon={MapPin}
                title="Location"
                lines={[{ text: "Pimville Zone 6, Pimville, 1809, South Africa" }]}
              />

              <div className="rounded-2xl gradient-hero p-6 text-white shadow-soft">
                <h3 className="text-lg font-semibold">Office hours</h3>
                <p className="mt-2 text-sm text-primary-foreground/80">
                  Monday – Friday, 08:00 – 17:00 SAST<br />
                  Saturday, 08:00 – 13:00 SAST
                </p>
              </div>
            </div>
          </Reveal>

          <Reveal delay={120}>
            <form
              onSubmit={onSubmit}
              className="rounded-3xl border border-border bg-card p-6 shadow-elegant md:p-8"
              noValidate
            >
              {sent ? (
                <div className="flex flex-col items-center gap-4 py-12 text-center">
                  <CheckCircle2 className="h-12 w-12 text-primary" />
                  <h3 className="text-xl font-semibold">Thanks — your message is on its way.</h3>
                  <p className="max-w-sm text-sm text-muted-foreground">
                    Your email app should have opened. If not, please reach us at info@ssgedge.co.za.
                  </p>
                </div>
              ) : (
                <>
                  <h2 className="text-2xl font-bold">Send a message</h2>
                  <p className="mt-1 text-sm text-muted-foreground">We'll respond within one business day.</p>
                  <div className="mt-6 grid gap-4 sm:grid-cols-2">
                    <Field label="Name" id="name" error={errors.name}>
                      <input
                        id="name"
                        type="text"
                        value={values.name}
                        onChange={(e) => update("name", e.target.value)}
                        maxLength={100}
                        className="input-base"
                        placeholder="Your full name"
                      />
                    </Field>
                    <Field label="Email" id="email" error={errors.email}>
                      <input
                        id="email"
                        type="email"
                        value={values.email}
                        onChange={(e) => update("email", e.target.value)}
                        maxLength={255}
                        className="input-base"
                        placeholder="you@example.com"
                      />
                    </Field>
                    <Field label="Phone number" id="phone" error={errors.phone} className="sm:col-span-2">
                      <input
                        id="phone"
                        type="tel"
                        value={values.phone}
                        onChange={(e) => update("phone", e.target.value)}
                        maxLength={30}
                        className="input-base"
                        placeholder="+27 ..."
                      />
                    </Field>
                    <Field label="Message" id="message" error={errors.message} className="sm:col-span-2">
                      <textarea
                        id="message"
                        rows={5}
                        value={values.message}
                        onChange={(e) => update("message", e.target.value)}
                        maxLength={1000}
                        className="input-base resize-y"
                        placeholder="Tell us about your project..."
                      />
                    </Field>
                  </div>

                  <button
                    type="submit"
                    disabled={submitting}
                    className="mt-6 inline-flex w-full items-center justify-center gap-2 rounded-full gradient-primary px-6 py-3 text-sm font-semibold text-primary-foreground shadow-soft transition-transform hover:-translate-y-0.5 disabled:opacity-60 sm:w-auto"
                  >
                    {submitting ? "Sending..." : (<>Send message <Send className="h-4 w-4" /></>)}
                  </button>
                </>
              )}
            </form>
          </Reveal>
        </div>
      </section>

      <style>{`
        .input-base {
          width: 100%;
          border-radius: 0.75rem;
          border: 1px solid var(--color-border);
          background: var(--color-background);
          padding: 0.7rem 0.9rem;
          font-size: 0.9rem;
          color: var(--color-foreground);
          outline: none;
          transition: border-color 200ms, box-shadow 200ms;
        }
        .input-base:focus {
          border-color: var(--color-ring);
          box-shadow: 0 0 0 4px color-mix(in oklab, var(--color-ring) 18%, transparent);
        }
      `}</style>
    </>
  );
}

function Field({
  label,
  id,
  error,
  className,
  children,
}: {
  label: string;
  id: string;
  error?: string;
  className?: string;
  children: React.ReactNode;
}) {
  return (
    <div className={className}>
      <label htmlFor={id} className="mb-1.5 block text-xs font-semibold uppercase tracking-wider text-foreground/70">
        {label}
      </label>
      {children}
      {error ? <p className="mt-1 text-xs text-destructive">{error}</p> : null}
    </div>
  );
}

function ContactCard({
  icon: Icon,
  title,
  lines,
}: {
  icon: React.ComponentType<{ className?: string }>;
  title: string;
  lines: { text: string; href?: string }[];
}) {
  return (
    <div className="flex items-start gap-4 rounded-2xl border border-border bg-card p-5 shadow-soft">
      <div className="grid h-11 w-11 shrink-0 place-items-center rounded-xl gradient-primary text-primary-foreground">
        <Icon className="h-5 w-5" />
      </div>
      <div className="min-w-0">
        <h3 className="text-sm font-semibold uppercase tracking-wider text-foreground/80">{title}</h3>
        <div className="mt-1 space-y-0.5 text-sm text-foreground">
          {lines.map((l, i) =>
            l.href ? (
              <a key={i} href={l.href} className="block truncate hover:text-primary">{l.text}</a>
            ) : (
              <p key={i}>{l.text}</p>
            ),
          )}
        </div>
      </div>
    </div>
  );
}
