"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { CheckCircle2, Loader2 } from "lucide-react";
import { z } from "zod";
import { formsApi } from "@/lib/api/forms";
import { ApiException } from "@/lib/api/client";
import { cn } from "@/lib/utils";
import {
  apiFieldErrors,
  emailField,
  fieldErrors,
  gstinField,
  mobileField,
  normalizeMobile,
  pincodeField,
  quantityField,
} from "@/lib/validation";
import FieldError from "@/components/ui/FieldError";
import { HOME_IMAGES } from "@/lib/home/images";
import { QUOTE_PREFILL_EVENT, type QuotePrefill } from "@/lib/home/quotePrefill";

const LABEL = "mb-1.5 block text-xs font-semibold uppercase tracking-wide text-gray-500";
const INPUT =
  "h-11 w-full rounded-xl border border-gray-200 bg-white px-3.5 text-sm text-gray-900 placeholder:text-gray-400 transition-all focus:border-[#CC1414] focus:outline-none focus:ring-2 focus:ring-[#CC1414]/20";

const PRODUCTS = [
  "MS TMT", "MS Angle", "MS Channel", "MS Pipe", "MS Round Bar", "MS Square Bar", "MS Flat",
  "MS Billet", "Sponge Iron", "HR Coil", "Aluminium Ingot", "Copper Wire", "Cement",
];

/**
 * Mirrors the `/enquiry` rules in the API (B01/B02): the backend rejects the
 * same values, this just says so under the field before the round trip.
 */
const leadSchema = z.object({
  name: z.string().trim().min(1, "Enter your name"),
  mobile: mobileField(),
  product: z.string().trim().min(1, "Select a product"),
  quantity: quantityField(),
  company: z.string().optional(),
  gst: gstinField(false),
  pincode: pincodeField(false),
  email: emailField(false),
  message: z.string().optional(),
});

type LeadErrors = Partial<Record<keyof typeof EMPTY_FORM, string>>;

/** API field name → form field name, for showing a 422 under the right input. */
const API_FIELD: Record<string, keyof typeof EMPTY_FORM> = {
  name: "name",
  contact_number: "mobile",
  product: "product",
  quantity: "quantity",
  company_name: "company",
  gst_number: "gst",
  pincode: "pincode",
  delivery_location: "pincode",
  email: "email",
  message: "message",
};

const EMPTY_FORM = {
  name: "",
  product: "",
  quantity: "",
  company: "",
  gst: "",
  pincode: "",
  email: "",
  mobile: "",
  message: "",
};

export default function LeadForm() {
  const [form, setForm] = useState(EMPTY_FORM);
  const [submitted, setSubmitted] = useState(false);
  const [reference, setReference] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [errors, setErrors] = useState<LeadErrors>({});
  const [loading, setLoading] = useState(false);
  const nameRef = useRef<HTMLInputElement>(null);

  /** Edit one field and clear its error, so a corrected value stops shouting. */
  const update = (key: keyof typeof EMPTY_FORM, value: string) => {
    setForm((f) => ({ ...f, [key]: value }));
    setErrors((e) => (e[key] ? { ...e, [key]: undefined } : e));
  };

  // The hero's quick-quote card hands over what the visitor already picked.
  useEffect(() => {
    const onPrefill = (event: Event) => {
      const { product, quantity, pincode } = (event as CustomEvent<QuotePrefill>).detail ?? {};
      setSubmitted(false);
      setForm((f) => ({
        ...f,
        product: product || f.product,
        // The hero sends free text ("25 MT"); keep just the number.
        quantity: quantity ? quantity.replace(/[^\d.]/g, "") : f.quantity,
        pincode: pincode || f.pincode,
      }));
      // After the smooth scroll settles, so the jump doesn't fight it.
      window.setTimeout(() => nameRef.current?.focus({ preventScroll: true }), 600);
    };
    window.addEventListener(QUOTE_PREFILL_EVENT, onPrefill);
    return () => window.removeEventListener(QUOTE_PREFILL_EVENT, onPrefill);
  }, []);

  // A search with no results links here as /?product=…#get-quote (B06).
  useEffect(() => {
    const product = new URLSearchParams(window.location.search).get("product")?.trim();
    if (product) setForm((f) => ({ ...f, product: product.slice(0, 100) }));
  }, []);

  // A prefilled product that isn't in the list still needs to be selectable.
  const productOptions = form.product && form.product !== "other" && !PRODUCTS.includes(form.product)
    ? [form.product, ...PRODUCTS]
    : PRODUCTS;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    const clientErrors = fieldErrors(leadSchema, form) as LeadErrors;
    setErrors(clientErrors);
    if (Object.keys(clientErrors).length > 0) return;

    setLoading(true);
    try {
      // Lands in admin under Product Enquiry -> General Enquiry.
      const res = await formsApi.enquiry({
        name: form.name.trim(),
        email: form.email.trim() || undefined,
        contact_number: normalizeMobile(form.mobile),
        company_name: form.company || undefined,
        gst_number: form.gst || undefined,
        product: form.product,
        quantity: form.quantity,
        quantity_unit: "MT",
        pincode: form.pincode || undefined,
        message: form.message || undefined,
      });
      setReference(res.data?.reference ?? null);
      setSubmitted(true);
    } catch (err) {
      if (err instanceof ApiException && err.status === 422 && err.errors) {
        const mapped: LeadErrors = {};
        for (const [key, message] of Object.entries(apiFieldErrors(err.errors))) {
          const field = API_FIELD[key];
          if (field && message && !mapped[field]) mapped[field] = message;
        }
        setErrors(mapped);
        if (Object.keys(mapped).length === 0) setError(err.message);
      } else {
        setError(err instanceof Error ? err.message : "Could not submit your requirement. Please try again.");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <section id="get-quote" className="relative isolate scroll-mt-24 overflow-hidden section-padding">
      <Image src={HOME_IMAGES.heroHotRolling} alt="" fill sizes="100vw" className="-z-10 object-cover" />
      <div className="absolute inset-0 -z-10 bg-gradient-to-br from-slate-950/95 via-slate-950/85 to-[#5c0909]/90" />
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="grid grid-cols-1 gap-10 lg:grid-cols-[0.8fr_1.2fr] lg:gap-14 items-start">
          {/* Left */}
          <div className="text-white lg:pt-6">
            <span className="text-[#ff6b6b] text-sm font-semibold uppercase tracking-wider">
              Get Started
            </span>
            <h2 className="text-3xl md:text-5xl font-black mt-2 mb-4 tracking-tight">
              Tell Us Your Requirements
            </h2>
            <p className="text-white/70 mb-8 text-lg">
              Best Rates | Working Capital | Delivery Anywhere
            </p>

            {/* Benefits */}
            <div className="space-y-3">
              {[
                "Get quotes within 30 minutes from verified suppliers",
                "Compare competing offers and pick the best landed price",
                "Flexible payment terms & working capital options",
                "Pan India delivery through verified transporters",
                "Dedicated relationship manager assigned",
              ].map((benefit) => (
                <div key={benefit} className="flex items-start gap-3">
                  <CheckCircle2 size={18} className="text-[#ff6b6b] mt-0.5 shrink-0" />
                  <span className="text-white/85 text-[15px]">{benefit}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Form */}
          <div className="bg-white rounded-3xl p-5 sm:p-8 shadow-2xl ring-1 ring-black/5">
            {submitted ? (
              <div className="text-center py-8">
                <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                  <CheckCircle2 size={32} className="text-green-600" />
                </div>
                <h3 className="text-xl font-bold text-gray-900 mb-2">
                  Request Submitted!
                </h3>
                <p className="text-gray-500 text-sm mb-2">
                  Our team will reach out to you within 30 minutes with the best quotes.
                </p>
                {reference && (
                  <p className="text-gray-400 text-xs mb-6">
                    Reference: <span className="font-semibold text-gray-600">{reference}</span>
                  </p>
                )}
                <button
                  onClick={() => { setSubmitted(false); setReference(null); setForm(EMPTY_FORM); }}
                  className="text-[#CC1414] font-semibold text-sm hover:underline"
                >
                  Submit Another Request
                </button>
              </div>
            ) : (
              <form onSubmit={handleSubmit} noValidate>
                <div className="mb-6">
                  <h3 className="text-xl font-bold text-gray-900 sm:text-2xl">Get Best Quotes — Free</h3>
                  <p className="mt-1 text-sm text-gray-500">
                    Share a few details and verified sellers will quote within 30 minutes.
                  </p>
                </div>

                {/* col-6 / col-6 from sm up; the message spans both columns. */}
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                  <div>
                    <label htmlFor="lead-name" className={LABEL}>
                      Name *
                    </label>
                    <input
                      id="lead-name"
                      ref={nameRef}
                      required
                      type="text"
                      autoComplete="name"
                      placeholder="Your full name"
                      value={form.name}
                      aria-invalid={!!errors.name}
                      aria-describedby="lead-name-err"
                      onChange={(e) => update("name", e.target.value)}
                      className={INPUT}
                    />
                    <FieldError id="lead-name-err" message={errors.name} />
                  </div>

                  <div>
                    <label htmlFor="lead-mobile" className={LABEL}>
                      Mobile Number *
                    </label>
                    <div className="flex">
                      <span className="inline-flex shrink-0 items-center rounded-l-xl border border-r-0 border-gray-200 bg-gray-50 px-3 text-sm font-medium text-gray-600">
                        +91
                      </span>
                      <input
                        id="lead-mobile"
                        required
                        type="tel"
                        inputMode="numeric"
                        autoComplete="tel-national"
                        placeholder="10-digit mobile"
                        maxLength={10}
                        value={form.mobile}
                        aria-invalid={!!errors.mobile}
                        aria-describedby="lead-mobile-err"
                        onChange={(e) => update("mobile", e.target.value.replace(/\D/g, ""))}
                        className={cn(INPUT, "min-w-0 rounded-l-none")}
                      />
                    </div>
                    <FieldError id="lead-mobile-err" message={errors.mobile} />
                  </div>

                  <div>
                    <label htmlFor="lead-product" className={LABEL}>
                      Product *
                    </label>
                    <select
                      id="lead-product"
                      required
                      value={form.product}
                      aria-invalid={!!errors.product}
                      aria-describedby="lead-product-err"
                      onChange={(e) => update("product", e.target.value)}
                      className={cn(INPUT, !form.product && "text-gray-400")}
                    >
                      <option value="">Select product</option>
                      {productOptions.map((p) => (
                        <option key={p} value={p} className="text-gray-900">
                          {p}
                        </option>
                      ))}
                      <option value="other" className="text-gray-900">
                        Other
                      </option>
                    </select>
                    <FieldError id="lead-product-err" message={errors.product} />
                  </div>

                  <div>
                    <label htmlFor="lead-quantity" className={LABEL}>
                      Quantity (MT) *
                    </label>
                    <div className="flex">
                      <input
                        id="lead-quantity"
                        required
                        type="text"
                        inputMode="decimal"
                        placeholder="e.g. 100"
                        value={form.quantity}
                        aria-invalid={!!errors.quantity}
                        aria-describedby="lead-quantity-err"
                        onChange={(e) => update("quantity", e.target.value.replace(/[^\d.]/g, ""))}
                        className={cn(INPUT, "min-w-0 rounded-r-none")}
                      />
                      <span className="inline-flex shrink-0 items-center rounded-r-xl border border-l-0 border-gray-200 bg-gray-50 px-3 text-sm font-medium text-gray-600">
                        MT
                      </span>
                    </div>
                    <FieldError id="lead-quantity-err" message={errors.quantity} />
                  </div>

                  <div>
                    <label htmlFor="lead-company" className={LABEL}>
                      Company
                    </label>
                    <input
                      id="lead-company"
                      type="text"
                      autoComplete="organization"
                      placeholder="Your company name"
                      value={form.company}
                      onChange={(e) => update("company", e.target.value)}
                      className={INPUT}
                    />
                  </div>

                  <div>
                    <label htmlFor="lead-gst" className={LABEL}>
                      GST Number
                    </label>
                    <input
                      id="lead-gst"
                      type="text"
                      placeholder="15-digit GSTIN"
                      maxLength={15}
                      value={form.gst}
                      aria-invalid={!!errors.gst}
                      aria-describedby="lead-gst-err"
                      onChange={(e) => update("gst", e.target.value.toUpperCase().replace(/[^0-9A-Z]/g, ""))}
                      className={INPUT}
                    />
                    <FieldError id="lead-gst-err" message={errors.gst} />
                  </div>

                  <div>
                    <label htmlFor="lead-email" className={LABEL}>
                      Email
                    </label>
                    <input
                      id="lead-email"
                      type="email"
                      autoComplete="email"
                      placeholder="Work email address"
                      value={form.email}
                      aria-invalid={!!errors.email}
                      aria-describedby="lead-email-err"
                      onChange={(e) => update("email", e.target.value)}
                      className={INPUT}
                    />
                    <FieldError id="lead-email-err" message={errors.email} />
                  </div>

                  <div>
                    <label htmlFor="lead-pincode" className={LABEL}>
                      Delivery Pincode
                    </label>
                    <input
                      id="lead-pincode"
                      type="text"
                      inputMode="numeric"
                      autoComplete="postal-code"
                      placeholder="6-digit pincode"
                      maxLength={6}
                      value={form.pincode}
                      aria-invalid={!!errors.pincode}
                      aria-describedby="lead-pincode-err"
                      onChange={(e) => update("pincode", e.target.value.replace(/\D/g, ""))}
                      className={INPUT}
                    />
                    <FieldError id="lead-pincode-err" message={errors.pincode} />
                  </div>

                  <div className="sm:col-span-2">
                    <label htmlFor="lead-message" className={LABEL}>
                      Message
                    </label>
                    <textarea
                      id="lead-message"
                      rows={3}
                      placeholder="Anything else we should know — grade, delivery window, payment terms"
                      value={form.message}
                      onChange={(e) => update("message", e.target.value)}
                      className={cn(INPUT, "h-auto resize-none py-3")}
                    />
                  </div>
                </div>

                {error && (
                  <p role="alert" className="mt-4 rounded-lg bg-red-50 px-3 py-2 text-xs font-medium text-[#CC1414]">
                    {error}
                  </p>
                )}

                <button
                  type="submit"
                  disabled={loading}
                  className="mt-6 flex w-full items-center justify-center gap-2 rounded-xl bg-[#CC1414] py-3.5 text-sm font-bold text-white shadow-md transition-colors hover:bg-[#A50E0E] hover:shadow-lg disabled:opacity-70"
                >
                  {loading ? (
                    <>
                      <Loader2 size={16} className="animate-spin" />
                      Submitting...
                    </>
                  ) : (
                    "Submit Requirement →"
                  )}
                </button>

                <p className="mt-3 text-center text-xs text-gray-400">
                  By submitting, you agree to our{" "}
                  <Link href="/terms" className="text-[#CC1414] hover:underline">
                    Terms & Privacy Policy
                  </Link>
                </p>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
