/**
 * booking.jsx — Step 5 (Book) of the Virtual Estimate flow.
 *
 * Triggered when the user clicks any tier CTA on the Results screen.
 * Collects contact info + a requested cleaning date, then shows a
 * confirmation message. Submission is mocked — a real backend would
 * route this to the local franchise.
 *
 * The selectedService prop carries { tier, name, price } so the heading
 * + "thanks, we'll confirm" copy can reference the chosen plan.
 *
 * Form fields per the brief:
 *   First Name*, Last Name*, Email*, Phone Number*, requested clean date*
 *   SMS opt-in checkbox + Neighborly legal disclosure
 */

function BookingStep({
  selectedService,
  property,
  address,
  onBack,
  onReset,
}) {
  const { useState, useMemo } = React;

  // Form state — kept flat for simple controlled inputs.
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName]   = useState('');
  const [email, setEmail]         = useState('');
  const [phone, setPhone]         = useState('');
  const [date, setDate]           = useState('');
  const [smsOptIn, setSmsOptIn]   = useState(false);
  const [errors, setErrors]       = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [sent, setSent]           = useState(false);

  // Earliest allowed cleaning date = tomorrow. Franchises confirm in 1 biz
  // day so same-day bookings aren't realistic via this form.
  const minDate = useMemo(() => {
    const d = new Date();
    d.setDate(d.getDate() + 1);
    return d.toISOString().slice(0, 10);
  }, []);

  // Pretty-print whatever ISO date the input gives us. We assemble in
  // local time so "Mon, Dec 9" matches what the user typed.
  function formatDate(iso) {
    if (!iso) return '';
    const [y, m, d] = iso.split('-').map(Number);
    const dt = new Date(y, m - 1, d);
    return dt.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' });
  }

  // Light-touch phone formatter — (555) 555-5555 as the user types. Strips
  // everything but digits, then reflows; if they paste a foreign-format
  // number we still pass it through but cap at 10 digits.
  function formatPhone(input) {
    const digits = String(input).replace(/\D/g, '').slice(0, 10);
    if (digits.length === 0) return '';
    if (digits.length < 4) return `(${digits}`;
    if (digits.length < 7) return `(${digits.slice(0,3)}) ${digits.slice(3)}`;
    return `(${digits.slice(0,3)}) ${digits.slice(3,6)}-${digits.slice(6)}`;
  }

  function validate() {
    const e = {};
    if (!firstName.trim()) e.firstName = 'Required';
    if (!lastName.trim())  e.lastName  = 'Required';
    if (!email.trim()) e.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())) e.email = 'Enter a valid email';
    const digits = phone.replace(/\D/g, '');
    if (!digits) e.phone = 'Required';
    else if (digits.length < 10) e.phone = 'Enter a 10-digit number';
    if (!date) e.date = 'Pick a date';
    return e;
  }

  async function handleSubmit(ev) {
    ev.preventDefault();
    const v = validate();
    setErrors(v);
    if (Object.keys(v).length > 0) {
      // Focus the first field with an error so screen-readers + keyboard
      // users land where they need to.
      const first = Object.keys(v)[0];
      const el = document.getElementById(`booking-${first}`);
      if (el) el.focus();
      return;
    }
    setSubmitting(true);
    // Mock network delay — a real impl would POST to /api/booking-request.
    await new Promise(r => setTimeout(r, 900));
    setSubmitting(false);
    setSent(true);
  }

  // ── Sent state ──────────────────────────────────────────────────────────
  if (sent) {
    return (
      <div className="card booking-success">
        <div className="booking-success__icon" aria-hidden="true">
          <CheckIcon size={28} color="#fff" />
        </div>
        <p className="section-eyebrow">Request Sent</p>
        <h2 className="card__title booking-success__title">
          Thanks, {firstName}! Your request is on its way.
        </h2>
        <p className="card__sub booking-success__lede">
          Your local Molly Maid team will reach out within <strong>1 business day</strong> at{' '}
          <strong>{phone}</strong> to confirm pricing and lock in your first clean.
        </p>

        <div className="booking-success__details">
          <dl>
            <div><dt>Plan</dt><dd>{selectedService?.name}</dd></div>
            <div><dt>Address</dt><dd>{address}</dd></div>
            <div><dt>Requested date</dt><dd>{formatDate(date)}</dd></div>
            <div><dt>Contact</dt><dd>{email}</dd></div>
          </dl>
        </div>

        <div className="btn-row" style={{ justifyContent: 'center' }}>
          <button type="button" className="btn-secondary" onClick={onBack}>
            Back to Estimate
          </button>
          <button type="button" className="btn-tertiary" onClick={onReset}>
            Start a new estimate
          </button>
        </div>
      </div>
    );
  }

  // ── Form state ──────────────────────────────────────────────────────────
  const verb = selectedService?.tier === 'regular' ? 'Booking' : 'Joining';
  const priceStr = selectedService
    ? window.MollyUtils.formatPrice(selectedService.price)
    : null;

  return (
    <div className="card booking-card">
      <div className="card__head">
        <p className="section-eyebrow">Step 5 · Almost Done</p>
        <h2 className="card__title">Let's get started!</h2>
        <p className="card__sub">
          Share a few details and your local Molly Maid team will reach out within
          <strong> 1 business day</strong> to confirm pricing and finalize your first clean.
          We won't charge anything yet — this just gets you on the schedule.
        </p>

        {selectedService && (
          <div className="booking-summary">
            <div className="booking-summary__tier">
              <span className="booking-summary__verb">{verb}</span>
              <span className="booking-summary__name">{selectedService.name}</span>
            </div>
            <div className="booking-summary__price">
              {priceStr}<small> / clean</small>
            </div>
          </div>
        )}
      </div>

      <form onSubmit={handleSubmit} noValidate>
        <p className="booking-required">
          <span aria-hidden="true">*</span> indicates a required field
        </p>

        <div className="booking-grid">
          <div className="field">
            <label htmlFor="booking-firstName">First Name<span className="req">*</span></label>
            <input
              id="booking-firstName"
              type="text"
              placeholder="ex. Jane"
              autoComplete="given-name"
              value={firstName}
              onChange={(e) => setFirstName(e.target.value)}
              aria-invalid={!!errors.firstName}
              aria-describedby={errors.firstName ? 'err-firstName' : undefined}
            />
            {errors.firstName && <p id="err-firstName" className="field__error">{errors.firstName}</p>}
          </div>

          <div className="field">
            <label htmlFor="booking-lastName">Last Name<span className="req">*</span></label>
            <input
              id="booking-lastName"
              type="text"
              placeholder="ex. Smith"
              autoComplete="family-name"
              value={lastName}
              onChange={(e) => setLastName(e.target.value)}
              aria-invalid={!!errors.lastName}
              aria-describedby={errors.lastName ? 'err-lastName' : undefined}
            />
            {errors.lastName && <p id="err-lastName" className="field__error">{errors.lastName}</p>}
          </div>

          <div className="field">
            <label htmlFor="booking-email">Email<span className="req">*</span></label>
            <input
              id="booking-email"
              type="email"
              inputMode="email"
              placeholder="ex. jane.smith@example.com"
              autoComplete="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              aria-invalid={!!errors.email}
              aria-describedby={errors.email ? 'err-email' : undefined}
            />
            {errors.email && <p id="err-email" className="field__error">{errors.email}</p>}
          </div>

          <div className="field">
            <label htmlFor="booking-phone">Phone Number<span className="req">*</span></label>
            <input
              id="booking-phone"
              type="tel"
              inputMode="tel"
              placeholder="(555) 555-5555"
              autoComplete="tel"
              value={phone}
              onChange={(e) => setPhone(formatPhone(e.target.value))}
              aria-invalid={!!errors.phone}
              aria-describedby={errors.phone ? 'err-phone' : undefined}
            />
            {errors.phone && <p id="err-phone" className="field__error">{errors.phone}</p>}
          </div>

          <div className="field booking-grid__full">
            <label htmlFor="booking-date">Requested First Cleaning Date<span className="req">*</span></label>
            <input
              id="booking-date"
              type="date"
              min={minDate}
              value={date}
              onChange={(e) => setDate(e.target.value)}
              aria-invalid={!!errors.date}
              aria-describedby={errors.date ? 'err-date' : 'hint-date'}
            />
            {errors.date
              ? <p id="err-date" className="field__error">{errors.date}</p>
              : <p id="hint-date" className="field__hint">
                  Your team will confirm or suggest the closest available slot.
                </p>}
          </div>
        </div>

        {/* SMS opt-in — Neighborly legal copy per the brief. */}
        <label className="booking-checkbox">
          <input
            type="checkbox"
            checked={smsOptIn}
            onChange={(e) => setSmsOptIn(e.target.checked)}
          />
          <span>
            <strong>Yes! You can text me service reminders and other messages.</strong>
            <span className="booking-checkbox__legal">
              By checking this box, I agree to opt in to receive automated SMS and/or
              MMS messages from Molly Maid, a Neighborly company, and its franchisees
              to the provided mobile number(s). Message data rates may apply. View{' '}
              <a href="#terms">Terms</a> and <a href="#privacy">Privacy Policy</a>.
              Reply STOP to opt out of future messages. Reply HELP for help.
            </span>
          </span>
        </label>

        <div className="btn-row">
          <button
            type="submit"
            className="btn-primary btn-primary--large"
            disabled={submitting}
          >
            {submitting ? 'Sending…' : 'Send Request'}
            {!submitting && <ArrowRightIcon size={16} color="#fff" />}
          </button>
          <button type="button" className="btn-tertiary" onClick={onBack} disabled={submitting}>
            Back to estimate
          </button>
        </div>
      </form>
    </div>
  );
}
