import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { Phone, Mail, MapPin, Send } from "lucide-react";
import { SITE } from "@/lib/site";
import { PageHeader } from "./about";

export const Route = createFileRoute("/contact")({
  head: () => ({
    meta: [
      { title: "Contact Pune Property Club — Baner, Pune Real Estate Advisors" },
      { name: "description", content: "Get in touch with Pune Property Club. Visit our office near Baner Hill or call +91 77090 24049 for a free consultation." },
    ],
  }),
  component: Contact,
});

function Contact() {
  const navigate = useNavigate();
  const [form, setForm] = useState({ name: "", email: "", phone: "", message: "", honeypot: "" });
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [busy, setBusy] = useState(false);

  const update = (k: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
    setForm((f) => ({ ...f, [k]: e.target.value }));

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (form.honeypot) return;
    const errs: Record<string, string> = {};
    if (form.name.trim().length < 2) errs.name = "Enter your name";
    if (!/^\S+@\S+\.\S+$/.test(form.email)) errs.email = "Enter a valid email";
    if (!/^[6-9]\d{9}$/.test(form.phone.replace(/\D/g, ""))) errs.phone = "10-digit Indian mobile";
    if (form.message.trim().length < 5) errs.message = "Tell us a bit more";
    setErrors(errs);
    if (Object.keys(errs).length) return;
    setBusy(true);
    try {
      await fetch("/api/public/lead", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...form, source: "contact-page" }),
      }).catch(() => {});
    } finally {
      navigate({ to: "/thank-you" });
    }
  };

  return (
    <div className="pb-20 md:pb-0">
      <PageHeader title="Get in Touch" subtitle="We'd love to help you find your next address. Reach out — we typically respond within an hour." />

      <section className="container mx-auto px-5 py-16 grid gap-8 lg:grid-cols-5 items-start">
        <form onSubmit={onSubmit} className="lg:col-span-3 lg:order-2 bg-card border border-gold/30 rounded-2xl p-6 md:p-8 shadow-luxury space-y-5 animate-fade-up">
          <h2 className="text-2xl font-bold">Send us a message</h2>
          <p className="text-sm text-muted-foreground -mt-3">Fill the form and our advisor will call you back within 1 hour.</p>
          <input type="text" value={form.honeypot} onChange={update("honeypot")} className="hidden" tabIndex={-1} autoComplete="off" aria-hidden />
          <div className="grid md:grid-cols-2 gap-5">
            <Field label="Full Name" error={errors.name}>
              <input value={form.name} onChange={update("name")} maxLength={80} className="input" placeholder="Your name" />
            </Field>
            <Field label="Mobile" error={errors.phone}>
              <input value={form.phone} onChange={update("phone")} maxLength={10} inputMode="numeric" className="input" placeholder="10-digit mobile" />
            </Field>
          </div>
          <Field label="Email" error={errors.email}>
            <input type="email" value={form.email} onChange={update("email")} maxLength={120} className="input" placeholder="you@example.com" />
          </Field>
          <Field label="Message" error={errors.message}>
            <textarea value={form.message} onChange={update("message")} rows={5} maxLength={1000} className="input resize-none" placeholder="Tell us what you're looking for — location, budget, timeline." />
          </Field>
          <button disabled={busy} type="submit" className="w-full inline-flex items-center justify-center gap-2 gradient-gold text-black font-semibold px-6 py-3.5 rounded-lg hover:shadow-luxury transition disabled:opacity-60">
            {busy ? "Sending..." : <>Send Message <Send size={16} /></>}
          </button>
        </form>

        <div className="lg:col-span-2 lg:order-1 grid gap-5 sm:grid-cols-2 lg:grid-cols-1">
          <ContactCard icon={Phone} title="Call Us" lines={[SITE.phoneDisplay, "Mon – Sat, 9:30 AM – 8:00 PM"]} href={`tel:${SITE.phone}`} />
          <ContactCard icon={Mail} title="Email Us" lines={[SITE.email, "Replies within 1 working hour"]} href={`mailto:${SITE.email}`} />
          <ContactCard icon={MapPin} title="Visit Office" lines={[SITE.address, "By appointment preferred"]} />
        </div>
      </section>

      <section className="container mx-auto px-5 pb-20">
        <div className="rounded-2xl overflow-hidden border border-border h-[400px] shadow-luxury">
          <iframe
            title="Pune Property Club office"
            src="https://www.google.com/maps?q=Baner+Hill+Pune&output=embed"
            className="w-full h-full border-0"
            loading="lazy"
          />
        </div>
      </section>

      <style>{`.input { width: 100%; background: var(--background); border: 1px solid var(--input); border-radius: 0.5rem; padding: 0.75rem 1rem; font-size: 0.95rem; outline: none; transition: border-color 0.2s; } .input:focus { border-color: var(--gold); }`}</style>
    </div>
  );
}

function Field({ label, error, children }: { label: string; error?: string; children: React.ReactNode }) {
  return (
    <div>
      <label className="text-xs uppercase tracking-wider font-medium text-muted-foreground">{label}</label>
      <div className="mt-1.5">{children}</div>
      {error && <p className="text-xs text-destructive mt-1">{error}</p>}
    </div>
  );
}

function ContactCard({ icon: Icon, title, lines, href }: { icon: typeof Phone; title: string; lines: string[]; href?: string }) {
  const content = (
    <div className="bg-card border border-border rounded-2xl p-6 hover-lift h-full">
      <div className="h-12 w-12 rounded-xl gradient-gold text-black flex items-center justify-center mb-4"><Icon size={20} /></div>
      <h3 className="font-bold text-lg">{title}</h3>
      {lines.map((l, i) => (
        <p key={i} className={i === 0 ? "mt-2 font-medium" : "text-sm text-muted-foreground"}>{l}</p>
      ))}
    </div>
  );
  return href ? <a href={href}>{content}</a> : content;
}
