import { createFileRoute } from "@tanstack/react-router";
import { motion } from "motion/react";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Mail, Phone, MapPin, Send, Check, AlertCircle } from "lucide-react";
import { PageHero } from "@/components/page-hero";
import { categories, CONTACT_EMAIL } from "@/lib/services";
import heroContact from "@/assets/hero-contact.jpg";

export const Route = createFileRoute("/contact")({
  head: () => ({
    meta: [
      { title: "Contact CyberData — Start a Project" },
      { name: "description", content: `Reach CyberData at ${CONTACT_EMAIL}. Tell us about your AI data, generative AI or enterprise data project — we'll respond within 24 hours.` },
      { property: "og:title", content: "Contact CyberData — Start a Project" },
      { property: "og:description", content: "Talk to our data operations team about your AI project." },
    ],
  }),
  component: Contact,
});

const schema = z.object({
  name: z.string().trim().min(2, "Please enter your name").max(100),
  email: z.string().trim().email("Enter a valid email").max(255),
  company: z.string().trim().max(150).optional().or(z.literal("")),
  service: z.string().min(1, "Please choose a service"),
  message: z.string().trim().min(10, "Tell us a bit more").max(2000),
});
type FormValues = z.infer<typeof schema>;

function Contact() {
  const [sent, setSent] = useState(false);
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors, isSubmitting },
  } = useForm<FormValues>({ resolver: zodResolver(schema) });

  const onSubmit = async (data: FormValues) => {
    const subject = `New project inquiry — ${data.service} — ${data.name}`;
    const body = [
      `Name: ${data.name}`,
      `Email: ${data.email}`,
      data.company ? `Company: ${data.company}` : null,
      `Service: ${data.service}`,
      "",
      "Message:",
      data.message,
    ]
      .filter(Boolean)
      .join("\n");

    const mailto = `mailto:${CONTACT_EMAIL}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    window.location.href = mailto;
    setSent(true);
    reset();
  };

  return (
    <>
      <PageHero
        eyebrow="Contact"
        title={<>Let's build something <span style={{ background: "var(--gradient-accent)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent" }}>intelligent</span> together.</>}
        subtitle="Tell us about your model, your data, and your timeline. We'll respond within 24 hours with a tailored plan."
        image={heroContact}
        imageAlt="Contact CyberData"
        height="sm"
      />

      <section className="mx-auto max-w-7xl px-6 py-20">
        <div className="grid gap-12 lg:grid-cols-[1fr_1.4fr]">
          <div>
            <h2 className="font-display text-3xl font-semibold tracking-tight text-balance">Get in touch directly.</h2>
            <p className="mt-4 text-muted-foreground text-pretty">
              Prefer email or a call? Reach us any time — we respond during business hours across
              global time zones.
            </p>
            <div className="mt-8 space-y-4">
              <a href={`mailto:${CONTACT_EMAIL}`} className="flex items-start gap-4 rounded-2xl border border-border bg-card p-5 hover:border-[var(--brand-teal-deep)] transition-colors">
                <div className="mt-0.5 inline-flex h-10 w-10 items-center justify-center rounded-xl" style={{ background: "var(--gradient-accent)" }}>
                  <Mail className="h-5 w-5 text-primary-foreground" />
                </div>
                <div>
                  <div className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">Email</div>
                  <div className="mt-0.5 font-medium">{CONTACT_EMAIL}</div>
                </div>
              </a>
              <div className="flex items-start gap-4 rounded-2xl border border-border bg-card p-5">
                <div className="mt-0.5 inline-flex h-10 w-10 items-center justify-center rounded-xl" style={{ background: "var(--gradient-accent)" }}>
                  <Phone className="h-5 w-5 text-primary-foreground" />
                </div>
                <div>
                  <div className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">Business hours</div>
                  <div className="mt-0.5 font-medium">Mon–Fri · 09:00 – 19:00 IST</div>
                </div>
              </div>
              <div className="flex items-start gap-4 rounded-2xl border border-border bg-card p-5">
                <div className="mt-0.5 inline-flex h-10 w-10 items-center justify-center rounded-xl" style={{ background: "var(--gradient-accent)" }}>
                  <MapPin className="h-5 w-5 text-primary-foreground" />
                </div>
                <div>
                  <div className="text-xs font-semibold uppercase tracking-widest text-muted-foreground">Delivery</div>
                  <div className="mt-0.5 font-medium">Global — secure delivery centers & remote teams</div>
                </div>
              </div>
            </div>
          </div>

          <motion.form
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
            onSubmit={handleSubmit(onSubmit)}
            className="rounded-3xl border border-border bg-card p-8 shadow-[var(--shadow-soft)] md:p-10"
          >
            <h3 className="font-display text-2xl font-semibold tracking-tight">Start a project</h3>
            <p className="mt-2 text-sm text-muted-foreground">
              Submitting this form opens your email client with the request pre-filled to{" "}
              <span className="font-medium text-foreground">{CONTACT_EMAIL}</span>.
            </p>

            <div className="mt-6 grid gap-5 md:grid-cols-2">
              <Field label="Full name" error={errors.name?.message}>
                <input {...register("name")} className="input" placeholder="Jane Doe" />
              </Field>
              <Field label="Work email" error={errors.email?.message}>
                <input type="email" {...register("email")} className="input" placeholder="jane@company.com" />
              </Field>
              <Field label="Company (optional)" error={errors.company?.message} className="md:col-span-2">
                <input {...register("company")} className="input" placeholder="Company Inc." />
              </Field>
              <Field label="Service of interest" error={errors.service?.message} className="md:col-span-2">
                <select {...register("service")} className="input" defaultValue="">
                  <option value="" disabled>
                    Select a service…
                  </option>
                  {categories.map((cat) => (
                    <optgroup key={cat.slug} label={cat.name}>
                      {cat.items.map((s) => (
                        <option key={s.slug} value={`${cat.name} — ${s.name}`}>
                          {s.name}
                        </option>
                      ))}
                    </optgroup>
                  ))}
                  <option value="Other / not sure">Other / not sure</option>
                </select>
              </Field>
              <Field label="Project details" error={errors.message?.message} className="md:col-span-2">
                <textarea {...register("message")} rows={5} className="input resize-none" placeholder="Tell us about your model, dataset, timeline and success criteria." />
              </Field>
            </div>

            {sent && (
              <div className="mt-6 flex items-center gap-2 rounded-xl border border-border bg-secondary/60 p-4 text-sm">
                <Check className="h-4 w-4" style={{ color: "var(--brand-teal-deep)" }} />
                Your email client should have opened with your inquiry ready to send. If it didn't, please email us at {CONTACT_EMAIL}.
              </div>
            )}
            {Object.keys(errors).length > 0 && !sent && (
              <div className="mt-6 flex items-center gap-2 rounded-xl border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">
                <AlertCircle className="h-4 w-4" /> Please fix the highlighted fields.
              </div>
            )}

            <button
              type="submit"
              disabled={isSubmitting}
              className="mt-6 inline-flex w-full items-center justify-center gap-2 rounded-full px-6 py-3.5 text-sm font-medium text-primary-foreground transition-transform hover:scale-[1.01] disabled:opacity-60 md:w-auto"
              style={{ background: "var(--gradient-accent)" }}
            >
              Send inquiry <Send className="h-4 w-4" />
            </button>
          </motion.form>
        </div>
      </section>

      <style>{`
        .input {
          width: 100%;
          border-radius: 0.75rem;
          border: 1px solid var(--color-border);
          background: var(--color-background);
          padding: 0.75rem 1rem;
          font-size: 0.9rem;
          color: var(--color-foreground);
          transition: border-color .15s, box-shadow .15s;
        }
        .input:focus {
          outline: none;
          border-color: var(--brand-teal-deep);
          box-shadow: 0 0 0 4px oklch(0.72 0.15 195 / 0.15);
        }
      `}</style>
    </>
  );
}

function Field({
  label,
  error,
  children,
  className,
}: {
  label: string;
  error?: string;
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <label className={`block ${className ?? ""}`}>
      <span className="mb-1.5 block text-xs font-semibold uppercase tracking-widest text-muted-foreground">
        {label}
      </span>
      {children}
      {error && <span className="mt-1 block text-xs text-destructive">{error}</span>}
    </label>
  );
}