"use client";

import { useRef, useState } from "react";
import { submitEnquiry } from "./actions";

const inputClass =
  "w-full rounded border border-stone-300 px-3 py-2.5 text-sm outline-none focus:border-brand focus:ring-1 focus:ring-brand";

export function EnquiryForm({
  areas,
  defaultArea,
  defaultType,
  propertyId,
}: {
  areas: { id: number; name: string }[];
  defaultArea?: string;
  defaultType?: string;
  propertyId?: number;
}) {
  const [step, setStep] = useState(1);
  const [step1Error, setStep1Error] = useState<string | null>(null);
  const step1Ref = useRef<HTMLDivElement>(null);

  function goToStep2() {
    const fields = step1Ref.current?.querySelectorAll<HTMLInputElement>("input[name=firstName],input[name=lastName],input[name=email],input[name=phone]");
    const missing = fields ? Array.from(fields).some((f) => f.value.trim() === "") : true;
    if (missing) {
      setStep1Error("Please fill in your name, email and phone before continuing.");
      return;
    }
    const email = step1Ref.current?.querySelector<HTMLInputElement>("input[name=email]");
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value)) {
      setStep1Error("Please enter a valid email address.");
      return;
    }
    setStep1Error(null);
    setStep(2);
  }

  return (
    <form action={submitEnquiry} className="rounded border border-stone-200 bg-white p-7">
      {propertyId && <input type="hidden" name="propertyId" value={propertyId} />}

      <div className="mb-7 flex gap-2">
        {[1, 2, 3].map((n) => (
          <div key={n} className={`h-1 flex-1 rounded-full ${n <= step ? "bg-brand" : "bg-stone-200"}`} />
        ))}
      </div>

      <div ref={step1Ref} className={step === 1 ? "" : "hidden"}>
        <p className="mb-4 text-xs text-stone-400">Step 1 of 3 — Your details</p>
        <div className="grid grid-cols-2 gap-3.5">
          <Field label="First name">
            <input name="firstName" className={inputClass} />
          </Field>
          <Field label="Last name">
            <input name="lastName" className={inputClass} />
          </Field>
        </div>
        <div className="mt-3.5 grid grid-cols-2 gap-3.5">
          <Field label="Email">
            <input name="email" type="email" className={inputClass} />
          </Field>
          <Field label="Phone">
            <input name="phone" type="tel" className={inputClass} />
          </Field>
        </div>
        <div className="mt-3.5">
          <Field label="Company (optional)">
            <input name="company" className={inputClass} />
          </Field>
        </div>
        {step1Error && <p className="mt-3 text-sm text-red-600">{step1Error}</p>}
      </div>

      <div className={step === 2 ? "" : "hidden"}>
        <p className="mb-4 text-xs text-stone-400">Step 2 of 3 — What you&apos;re looking for</p>
        <div className="grid grid-cols-2 gap-3.5">
          <Field label="Property type">
            <select name="propertyTypeInterest" defaultValue={defaultType ?? ""} className={inputClass}>
              <option value="">Any</option>
              <option value="OFFICE">Office</option>
              <option value="INDUSTRIAL">Industrial</option>
              <option value="RETAIL">Retail</option>
            </select>
          </Field>
          <Field label="Looking to">
            <select name="listingTypeInterest" defaultValue="" className={inputClass}>
              <option value="">Any</option>
              <option value="TO_LET">To Let</option>
              <option value="FOR_SALE">For Sale</option>
            </select>
          </Field>
        </div>
        <div className="mt-3.5 grid grid-cols-2 gap-3.5">
          <Field label="Area of interest">
            <input name="areaOfInterest" list="area-options" defaultValue={defaultArea ?? ""} placeholder="e.g. Sandton" className={inputClass} />
            <datalist id="area-options">
              {areas.map((a) => (
                <option key={a.id} value={a.name} />
              ))}
            </datalist>
          </Field>
          <Field label="Move-in timeline">
            <select name="moveInTimeline" defaultValue="" className={inputClass}>
              <option value="">Select</option>
              <option>Immediately</option>
              <option>1–3 months</option>
              <option>3–6 months</option>
              <option>6+ months</option>
            </select>
          </Field>
        </div>
        <div className="mt-3.5">
          <Field label="Message">
            <textarea name="message" rows={3} className={inputClass} />
          </Field>
        </div>
      </div>

      <div className={step === 3 ? "" : "hidden"}>
        <p className="mb-4 text-xs text-stone-400">Step 3 of 3 — Review &amp; submit</p>
        <p className="text-sm text-stone-600">
          We&apos;ll route this enquiry to the broker covering your area and property type, or to our general
          enquiries queue if there&apos;s no exact match.
        </p>
      </div>

      <div className="mt-6 flex justify-between border-t border-stone-100 pt-5">
        <button
          type="button"
          onClick={() => setStep((s) => Math.max(1, s - 1))}
          className={`rounded border border-stone-300 px-5 py-2.5 text-sm font-semibold text-stone-500 hover:border-brand hover:text-brand ${step === 1 ? "invisible" : ""}`}
        >
          Back
        </button>
        {step < 3 ? (
          <button
            type="button"
            onClick={() => (step === 1 ? goToStep2() : setStep(3))}
            className="rounded bg-brand px-6 py-2.5 text-sm font-bold text-white hover:bg-brand-deep"
          >
            Continue
          </button>
        ) : (
          <button type="submit" className="rounded bg-brand px-6 py-2.5 text-sm font-bold text-white hover:bg-brand-deep">
            Submit enquiry
          </button>
        )}
      </div>
    </form>
  );
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="flex flex-col gap-1.5">
      <span className="text-[11px] font-semibold tracking-wide text-stone-400 uppercase">{label}</span>
      {children}
    </label>
  );
}
