import { useState } from "react";
import { useForm } from "react-hook-form";
import { motion } from "framer-motion";
import { CheckCircle2, Loader2, Send, Phone, Mail, MapPin } from "lucide-react";
import { toast } from "sonner";
import { project } from "@/data/project";
import { submitEnquiry, type EnquiryPayload } from "@/lib/api";
import { SectionHeading } from "./SectionHeading";

interface FormValues {
  name: string;
  phone: string;
  email: string;
  message?: string;
}

export function EnquiryForm() {
  const [done, setDone] = useState(false);
  const { register, handleSubmit, formState: { errors, isSubmitting }, reset } = useForm<FormValues>();

  const onSubmit = async (values: FormValues) => {
    const payload: EnquiryPayload = { ...values, source: "website" };
    try {
      const res = await submitEnquiry(payload);
      if (res.success) {
        setDone(true);
        reset();
        if (res.partial) {
          toast.warning(res.message || "Enquiry submitted to ERP, but email notification failed.");
        } else {
          toast.success(res.message || "Thank you. Your enquiry has been submitted successfully.");
        }
        setTimeout(() => setDone(false), 4500);
      } else {
        toast.error(res.message || "Unable to submit enquiry. Please try again.");
      }
    } catch (err: any) {
      toast.error(err?.message || "Unable to submit enquiry. Please try again.");
    }
  };

  return (
    <section id="contact" className="relative overflow-hidden py-12 md:py-8 bg-secondary/40">
      {/* Full-width Heading at the top */}
      <div className="container-luxe mb-12">
        <SectionHeading
          align="center"
          eyebrow="Contact Us"
          title="Let's Connect"
          subtitle="Have questions about pricing, plot availability, or site visits? Our team is here to help you find the right investment."
        />
      </div>

      <div className="container-luxe grid items-center gap-12 lg:grid-cols-2 lg:gap-20">
        <div className="flex h-full flex-col justify-center space-y-8">
          {/* Card 1: Phone */}
          <div className="flex gap-4 rounded-3xl border border-border bg-secondary/50 p-6 shadow-soft transition-all duration-300 hover:shadow-luxe hover:border-gold/30">
            <div className="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-brand text-gold">
              <Phone className="h-6 w-6" />
            </div>
            <div>
              <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-muted-foreground">Call us</span>
              <a
                href={`tel:${project.contact.phone.replace(/\s+/g, "")}`}
                className="mt-1 block font-display text-xl font-bold text-brand hover:text-gold transition-colors"
              >
                {project.contact.phone}
              </a>
            </div>
          </div>

          {/* Card 2: Email */}
          <div className="flex gap-4 rounded-3xl border border-border bg-secondary/50 p-6 shadow-soft transition-all duration-300 hover:shadow-luxe hover:border-gold/30">
            <div className="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-brand text-gold">
              <Mail className="h-6 w-6" />
            </div>
            <div>
              <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-muted-foreground">Email</span>
              <a
                href="#contact-form"
                onClick={(e) => {
                  e.preventDefault();
                  document.getElementById("contact-form")?.scrollIntoView({ behavior: "smooth" });
                  const input = document.getElementById("name-input");
                  if (input) input.focus();
                }}
                className="mt-1 block text-lg font-bold text-brand hover:text-gold transition-colors"
              >
                {project.contact.email}
              </a>
              <p className="mt-1 text-xs text-muted-foreground">Click to write an inquiry below</p>
            </div>
          </div>

          {/* Card 3: Address */}
          <div className="flex gap-4 rounded-3xl border border-border bg-secondary/50 p-6 shadow-soft transition-all duration-300 hover:shadow-luxe hover:border-gold/30">
            <div className="grid h-12 w-12 shrink-0 place-items-center rounded-2xl bg-brand text-gold">
              <MapPin className="h-6 w-6" />
            </div>
            <div>
              <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-muted-foreground">Site Address</span>
              <div className="mt-1 text-sm font-semibold leading-relaxed text-brand">
                {project.contact.address.line1}, {project.contact.address.line2},<br />
                {project.contact.address.line3}, {project.contact.address.city} {project.contact.address.pincode}
              </div>
              <a
                href="#map"
                onClick={(e) => {
                  e.preventDefault();
                  document.getElementById("map")?.scrollIntoView({ behavior: "smooth" });
                }}
                className="mt-3 inline-flex items-center gap-1 text-xs font-semibold text-gold hover:underline"
              >
                View on Interactive Map &rarr;
              </a>
            </div>
          </div>
        </div>

        <motion.form
          id="contact-form"
          onSubmit={handleSubmit(onSubmit)}
          initial={{ opacity: 0, y: 24 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, margin: "-80px" }}
          transition={{ duration: 0.6 }}
          className="rounded-3xl bg-white p-6 shadow-luxe border border-border md:p-8"
          noValidate
        >
          <div className="mb-6 flex items-center justify-between">
            <div>
              <div className="text-xs font-semibold uppercase tracking-[0.18em] text-gold">Enquire now</div>
              {/* <div className="font-display text-xl font-semibold text-brand">We'll respond in under 30 minutes</div> */}
            </div>
          </div>

          <div className="space-y-4">
            <Field label="Full name" error={errors.name?.message}>
              <input
                id="name-input"
                {...register("name", { required: "Name is required", minLength: { value: 2, message: "Too short" } })}
                placeholder="Your name"
                className="input-luxe"
              />
            </Field>
            <Field label="Phone" error={errors.phone?.message}>
              <input
                {...register("phone", {
                  required: "Phone is required",
                  pattern: { value: /^[0-9+\-\s()]{8,15}$/, message: "Enter a valid phone" },
                })}
                placeholder="+91 9xxxx xxxxx"
                className="input-luxe"
              />
            </Field>
            <Field label="Email" error={errors.email?.message}>
              <input
                type="email"
                {...register("email", {
                  required: "Email is required",
                  pattern: { value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: "Enter a valid email" },
                })}
                placeholder="you@email.com"
                className="input-luxe"
              />
            </Field>
            <Field label="Message (optional)">
              <textarea
                rows={3}
                {...register("message", { maxLength: { value: 500, message: "Max 500 characters" } })}
                placeholder="I'm interested in a 1500 sq.ft plot…"
                className="input-luxe resize-none"
              />
            </Field>
          </div>

          <button
            type="submit"
            disabled={isSubmitting}
            className="mt-6 flex w-full items-center justify-center gap-2 rounded-full bg-cta py-3.5 text-sm font-semibold text-cta-foreground shadow-soft transition-transform hover:scale-[1.02] disabled:cursor-not-allowed disabled:opacity-70"
          >
            {isSubmitting ? <Loader2 className="h-4 w-4 animate-spin" /> : done ? <CheckCircle2 className="h-4 w-4" /> : <Send className="h-4 w-4" />}
            {isSubmitting ? "Submitting…" : done ? "Submitted successfully!" : "Submit Enquiry"}
          </button>
          <p className="mt-3 text-center text-[11px] text-muted-foreground">
            By submitting you agree to be contacted about Homeland Phase IV.
          </p>
        </motion.form>
      </div>

      <style>{`
        .input-luxe {
          width: 100%;
          border-radius: 0.75rem;
          border: 1px solid var(--border);
          background: var(--background);
          padding: 0.85rem 1rem;
          font-size: 0.95rem;
          color: var(--foreground);
          outline: none;
          transition: border-color .2s, box-shadow .2s;
        }
        .input-luxe::placeholder { color: oklch(0.65 0.01 240); }
        .input-luxe:focus { border-color: var(--gold); box-shadow: 0 0 0 3px color-mix(in oklab, var(--gold) 30%, transparent); }
      `}</style>
    </section>
  );
}

function Field({ label, error, children }: { label: string; error?: string; children: React.ReactNode }) {
  return (
    <label className="block">
      <span className="mb-1.5 block text-xs font-semibold uppercase tracking-[0.14em] text-brand">{label}</span>
      {children}
      {error ? <span className="mt-1 block text-xs text-cta">{error}</span> : null}
    </label>
  );
}
