/* Design reminder: Practical Navy + Mint Editorial. This embedded form uses crisp navy structure,
 * mint actions, high-contrast validation, and a calm, conversion-focused experience. */
import { useState, type FormEvent } from "react";
import { ArrowRight, CheckCircle2, Loader2, ShieldCheck } from "lucide-react";
import { submitLeadToCrm } from "@/lib/leadSubmission";
import { AddressAutocompleteInput } from "@/components/AddressAutocompleteInput";
import { formatUSPhoneInput } from "@shared/phone";

type FormValues = {
  address: string;
  name: string;
  phone: string;
  email: string;
  timeline: string;
};

const initialValues: FormValues = {
  address: "",
  name: "",
  phone: "",
  email: "",
  timeline: "asap",
};

export default function SellFastOfferForm() {
  const [values, setValues] = useState<FormValues>(initialValues);
  const [errors, setErrors] = useState<Partial<Record<keyof FormValues, string>>>({});
  const [status, setStatus] = useState<"idle" | "submitting" | "success" | "error">("idle");
  const [serverError, setServerError] = useState("");
  const [autocompleteUnavailable, setAutocompleteUnavailable] = useState(false);

  const update = (field: keyof FormValues, value: string) => {
    setValues((current) => ({ ...current, [field]: value }));
    if (errors[field]) setErrors((current) => ({ ...current, [field]: undefined }));
    if (status === "error") setStatus("idle");
    if (field === "address") setAutocompleteUnavailable(false);
  };

  const validate = () => {
    const nextErrors: Partial<Record<keyof FormValues, string>> = {};
    if (!values.address.trim()) nextErrors.address = "Enter the property address.";
    if (!values.name.trim()) nextErrors.name = "Enter your full name.";
    if (values.phone.replace(/\D/g, "").length < 10) nextErrors.phone = "Enter a valid 10-digit phone number.";
    if (values.email && !/^\S+@\S+\.\S+$/.test(values.email)) nextErrors.email = "Enter a valid email address.";
    setErrors(nextErrors);
    return Object.keys(nextErrors).length === 0;
  };

  const submit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!validate()) return;

    setStatus("submitting");
    setServerError("");

    try {
      const data = await submitLeadToCrm({
        propertyAddress: values.address,
        name: values.name,
        phone: values.phone,
        email: values.email,
        timeline: values.timeline,
        leadSource: "sell-your-house-fast-page",
        consent: false,
      });
      if (!data.success) throw new Error("We could not submit your request.");
      setStatus("success");
    } catch (error) {
      setStatus("error");
      setServerError("We could not submit your request just now. Please try again or call us.");
    }
  };

  if (status === "success") {
    return <div className="sell-fast-form__success" role="status" aria-live="polite"><CheckCircle2 size={38} /><div><h3>Thanks — your request was received.</h3><p>Original Home Buyers will review the information you shared and follow up about the property. There is no obligation to accept an offer.</p></div></div>;
  }

  return (
    <form className="sell-fast-form" onSubmit={submit} noValidate>
      <div className="sell-fast-form__head"><span className="eyebrow eyebrow--pill">FREE · NO OBLIGATION</span><h3>Request a cash offer for your property.</h3><p>Share a few details to start a direct, as-is sale conversation with Original Home Buyers.</p></div>
      <div className="sell-fast-form__grid">
        <label className="sell-fast-form__field sell-fast-form__field--full"><span>Property address <b>*</b></span><AddressAutocompleteInput id="sell-fast-address" name="address" autoComplete="street-address" placeholder="Start typing your U.S. property address" value={values.address} onValueChange={(value) => update("address", value)} onMapsReady={() => setAutocompleteUnavailable(false)} onMapsUnavailable={() => setAutocompleteUnavailable(true)} aria-invalid={Boolean(errors.address)} aria-describedby={errors.address ? "sell-fast-address-error" : "sell-fast-address-help"} />{errors.address ? <small id="sell-fast-address-error">{errors.address}</small> : <small id="sell-fast-address-help" className="sell-fast-form__helper">{autocompleteUnavailable ? "Suggestions are temporarily unavailable. You may enter the address manually." : "Choose an address from the U.S. suggestions as you type."}</small>}</label>
        <label className="sell-fast-form__field"><span>Full name <b>*</b></span><input name="name" autoComplete="name" placeholder="Your name" value={values.name} onChange={(event) => update("name", event.target.value)} aria-invalid={Boolean(errors.name)} aria-describedby={errors.name ? "sell-fast-name-error" : undefined} />{errors.name && <small id="sell-fast-name-error">{errors.name}</small>}</label>
        <label className="sell-fast-form__field"><span>Phone number <b>*</b></span><input name="phone" type="tel" inputMode="tel" autoComplete="tel-national" maxLength={14} placeholder="(000) 000-0000" value={values.phone} onChange={(event) => update("phone", formatUSPhoneInput(event.target.value))} aria-invalid={Boolean(errors.phone)} aria-describedby={errors.phone ? "sell-fast-phone-error" : undefined} />{errors.phone && <small id="sell-fast-phone-error">{errors.phone}</small>}</label>
        <label className="sell-fast-form__field"><span>Email <em>Optional</em></span><input name="email" type="email" autoComplete="email" placeholder="you@example.com" value={values.email} onChange={(event) => update("email", event.target.value)} aria-invalid={Boolean(errors.email)} aria-describedby={errors.email ? "sell-fast-email-error" : undefined} />{errors.email && <small id="sell-fast-email-error">{errors.email}</small>}</label>
        <label className="sell-fast-form__field"><span>Preferred timeline</span><select name="timeline" value={values.timeline} onChange={(event) => update("timeline", event.target.value)}><option value="asap">As soon as possible</option><option value="30days">Within 30 days</option><option value="flexible">Flexible or later</option></select></label>
      </div>
      {status === "error" && <p className="sell-fast-form__error" role="alert">{serverError}</p>}
      <div className="sell-fast-form__footer"><button className="button button--mint" type="submit" disabled={status === "submitting"}>{status === "submitting" ? <><Loader2 size={17} className="spin" /> Sending request…</> : <>Get My Cash Offer <ArrowRight size={17} /></>}</button><p><ShieldCheck size={16} /> Your details are used to respond to this request. <a href="/privacy.html">Privacy Policy</a></p></div>
    </form>
  );
}
