import { useState, type FormEvent } from "react";
import { createFileRoute, Link } from "@tanstack/react-router";
import { motion } from "motion/react";
import { z } from "zod";
import { Mail, Phone, Globe, Check } from "lucide-react";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import RollerReveal from "@/components/RollerReveal";

const TITLE = "Contact Us — Belarsen Quality Paints";
const DESC =
  "Tell us about your site and we'll help you choose the right texture, primer or finish. Call +91 9828898283 or send an enquiry.";

const SERVICES = [
  "Acrylic Primer",
  "Stoneio",
  "Ambrosia",
  "Rustik",
  "Super-Fine",
  "Fenofine",
  "Other",
];

const schema = z.object({
  name: z.string().trim().min(2, "Please enter your name").max(100),
  phone: z
    .string()
    .trim()
    .min(7, "Please enter a valid phone number")
    .max(20, "Phone number is too long"),
  email: z.string().trim().email("Please enter a valid email address").max(255),
  location: z.string().trim().min(2, "Please enter your city or site location").max(120),
  service: z.string().trim().min(1, "Please choose a product or service"),
  message: z.string().trim().min(10, "Tell us a little more (min. 10 characters)").max(1000),
});

type FormValues = z.infer<typeof schema>;

const EMPTY: FormValues = {
  name: "",
  phone: "",
  email: "",
  location: "",
  service: "",
  message: "",
};

export const Route = createFileRoute("/contact")({
  head: () => ({
    meta: [
      { title: TITLE },
      { name: "description", content: DESC },
      { property: "og:title", content: TITLE },
      { property: "og:description", content: DESC },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: ContactPage,
});

const fieldClass =
  "mt-2 w-full rounded-xl border border-ink/15 bg-plaster px-4 py-3 text-sm text-ink outline-none transition-colors placeholder:text-ink-muted/60 focus:border-brand";

function ContactPage() {
  const [values, setValues] = useState<FormValues>(EMPTY);
  const [errors, setErrors] = useState<Partial<Record<keyof FormValues, string>>>({});
  const [submitted, setSubmitted] = useState<FormValues | null>(null);

  const set = (key: keyof FormValues) => (v: string) => {
    setValues((prev) => ({ ...prev, [key]: v }));
    setErrors((prev) => ({ ...prev, [key]: undefined }));
  };

  const onSubmit = (e: FormEvent) => {
    e.preventDefault();
    const result = schema.safeParse(values);
    if (!result.success) {
      const next: Partial<Record<keyof FormValues, string>> = {};
      for (const issue of result.error.issues) {
        const key = issue.path[0] as keyof FormValues;
        if (!next[key]) next[key] = issue.message;
      }
      setErrors(next);
      return;
    }
    setSubmitted(result.data);
  };

  return (
    <div className="bg-plaster text-ink relative min-h-screen w-full overflow-x-clip">
      <div aria-hidden="true" className="grain-overlay" />
      <div aria-hidden="true" className="plaster-tooth fixed inset-0 z-[54]" />
      <Navbar forceLight />

      <main>
        <header className="border-ink/10 border-b bg-[linear-gradient(180deg,#252220_0%,#1c1a17_100%)] px-4 pt-40 pb-24 sm:px-6 lg:px-8">
          <div className="mx-auto max-w-5xl">
            <p className="text-brand text-xs font-bold tracking-[0.3em] uppercase">Contact</p>
            <RollerReveal
              as="div"
              className="mt-4 max-w-2xl text-4xl leading-[1.05] font-black tracking-tighter text-white sm:text-6xl"
            >
              <h1>
                Tell us about
                <span className="text-brand"> your site.</span>
              </h1>
            </RollerReveal>
            <p className="mt-6 max-w-xl text-sm leading-relaxed font-light text-gray-400">
              Share a few details and our team will recommend the right primer, texture or finish
              — with an estimate for your surface area.
            </p>
          </div>
        </header>

        <div className="mx-auto grid max-w-5xl gap-14 px-4 py-20 sm:px-6 lg:grid-cols-[1fr_minmax(0,1.4fr)] lg:px-8">
          <aside className="space-y-8">
            <div>
              <h2 className="text-xs font-bold tracking-widest uppercase">Reach us directly</h2>
              <ul className="mt-6 space-y-5 text-sm">
                <li className="flex items-start gap-3">
                  <Phone size={18} className="text-brand mt-0.5" aria-hidden="true" />
                  <a href="tel:+919828898283" className="hover:text-brand transition-colors">
                    +91 9828898283
                  </a>
                </li>
                <li className="flex items-start gap-3">
                  <Mail size={18} className="text-brand mt-0.5" aria-hidden="true" />
                  <a href="mailto:info@belarsen.com" className="hover:text-brand transition-colors">
                    info@belarsen.com
                  </a>
                </li>
                <li className="flex items-start gap-3">
                  <Globe size={18} className="text-brand mt-0.5" aria-hidden="true" />
                  <a href="https://www.belarsen.com" className="hover:text-brand transition-colors">
                    www.belarsen.com
                  </a>
                </li>
              </ul>
            </div>
            <div className="bg-sand border-ink/10 rounded-2xl border p-6">
              <p className="text-ink-soft text-sm leading-relaxed font-light">
                Serving builders, architects and homeowners across Rajasthan — 10+ years and 300+
                completed projects.
              </p>
            </div>
          </aside>

          {submitted ? (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, ease: [0.22, 1, 0.36, 1] }}
              className="border-ink/10 bg-sand rounded-3xl border p-8"
            >
              <div className="bg-brand flex h-12 w-12 items-center justify-center rounded-full text-white">
                <Check size={22} aria-hidden="true" />
              </div>
              <h2 className="mt-6 text-2xl font-black tracking-tight">Thank you, {submitted.name}.</h2>
              <p className="text-ink-soft mt-3 text-sm leading-relaxed font-light">
                Your enquiry has been captured below for your review. Nothing is stored or sent —
                for an immediate response, call us on{" "}
                <a href="tel:+919828898283" className="text-brand hover:underline">
                  +91 9828898283
                </a>
                .
              </p>
              <dl className="border-ink/10 mt-8 space-y-3 border-t pt-6 text-sm">
                {(
                  [
                    ["Name", submitted.name],
                    ["Phone", submitted.phone],
                    ["Email", submitted.email],
                    ["Location", submitted.location],
                    ["Interest", submitted.service],
                    ["Message", submitted.message],
                  ] as const
                ).map(([label, value]) => (
                  <div key={label} className="grid grid-cols-[90px_1fr] gap-3">
                    <dt className="text-ink-muted text-xs font-bold tracking-widest uppercase">
                      {label}
                    </dt>
                    <dd className="text-ink-soft font-light break-words">{value}</dd>
                  </div>
                ))}
              </dl>
              <button
                type="button"
                onClick={() => {
                  setSubmitted(null);
                  setValues(EMPTY);
                }}
                className="border-ink/15 hover:border-ink/40 mt-8 rounded-full border px-6 py-3 text-sm font-semibold transition-colors"
              >
                Send another enquiry
              </button>
            </motion.div>
          ) : (
            <form
              noValidate
              onSubmit={onSubmit}
              className="border-ink/10 bg-sand rounded-3xl border p-6 sm:p-8"
            >
              <div className="grid gap-6 sm:grid-cols-2">
                <Field label="Name" error={errors.name}>
                  <input
                    className={fieldClass}
                    value={values.name}
                    maxLength={100}
                    onChange={(e) => set("name")(e.target.value)}
                    placeholder="Your full name"
                    autoComplete="name"
                  />
                </Field>
                <Field label="Phone" error={errors.phone}>
                  <input
                    className={fieldClass}
                    value={values.phone}
                    maxLength={20}
                    onChange={(e) => set("phone")(e.target.value)}
                    placeholder="+91 …"
                    autoComplete="tel"
                    inputMode="tel"
                  />
                </Field>
                <Field label="Email" error={errors.email}>
                  <input
                    className={fieldClass}
                    value={values.email}
                    maxLength={255}
                    onChange={(e) => set("email")(e.target.value)}
                    placeholder="you@example.com"
                    autoComplete="email"
                    inputMode="email"
                  />
                </Field>
                <Field label="City / site location" error={errors.location}>
                  <input
                    className={fieldClass}
                    value={values.location}
                    maxLength={120}
                    onChange={(e) => set("location")(e.target.value)}
                    placeholder="Jaipur, Rajasthan"
                  />
                </Field>
                <div className="sm:col-span-2">
                  <Field label="Product / service of interest" error={errors.service}>
                    <select
                      className={fieldClass}
                      value={values.service}
                      onChange={(e) => set("service")(e.target.value)}
                    >
                      <option value="">Select an option</option>
                      {SERVICES.map((s) => (
                        <option key={s} value={s}>
                          {s}
                        </option>
                      ))}
                    </select>
                  </Field>
                </div>
                <div className="sm:col-span-2">
                  <Field label="Message" error={errors.message}>
                    <textarea
                      rows={5}
                      className={`${fieldClass} resize-y`}
                      value={values.message}
                      maxLength={1000}
                      onChange={(e) => set("message")(e.target.value)}
                      placeholder="Surface area, type of building, timeline…"
                    />
                  </Field>
                </div>
              </div>

              <button
                type="submit"
                className="bg-brand mt-8 w-full rounded-full px-7 py-3.5 text-sm font-semibold text-white transition-transform duration-300 hover:scale-[1.02] hover:shadow-[0_0_28px_rgba(239,59,54,0.45)] active:scale-95 sm:w-auto"
              >
                Submit enquiry
              </button>

              <p className="text-ink-muted mt-4 text-xs leading-relaxed font-light">
                By Submitting the form, I agree to the{" "}
                <Link to="/privacy-policy" className="text-brand font-medium hover:underline">
                  Privacy Policy
                </Link>{" "}
                and website{" "}
                <Link to="/terms" className="text-brand font-medium hover:underline">
                  Terms of Use
                </Link>
                .
              </p>
            </form>
          )}
        </div>
      </main>

      <Footer />
    </div>
  );
}

function Field({
  label,
  error,
  children,
}: {
  label: string;
  error?: string | undefined;
  children: React.ReactNode;
}) {
  return (
    <label className="block">
      <span className="text-xs font-bold tracking-widest uppercase">{label}</span>
      {children}
      {error && <span className="text-brand mt-2 block text-xs font-medium">{error}</span>}
    </label>
  );
}
