import React from 'react';
import DynamicFields from '../DynamicFields';

function isEmptyValue(val, type) {
  if (type === 'checkbox') return !val;
  if (val === undefined || val === null) return true;
  if (Array.isArray(val)) return val.length === 0;
  return String(val).trim() === '';
}

function normalizeId(def) {
  return def?.id || def?.field_key || def?.name_key || '';
}

function layoutFromDefs(defs = []) {
  return defs
    .map((d) => ({
      id: normalizeId(d),
      required: !!(d?.is_required ?? d?.required ?? false),
      width: 'full',
    }))
    .filter((d) => d.id);
}

export default function StepCustomer({
  formFields,
  answers,
  onChange,
  onBack,
  onNext,
  onError,
  layout,
  backLabel = '<- Back',
  nextLabel = 'Next ->',
}) {
  const customerDefs = formFields?.customer || [];
  const bookingDefs = formFields?.booking || [];
  const hasBookingSection = bookingDefs.length > 0;
  const requiredCustomerCount = customerDefs.filter((def) => !!(def?.is_required ?? def?.required)).length;
  const completedRequiredCustomerCount = customerDefs.reduce((count, def) => {
    const required = !!(def?.is_required ?? def?.required);
    if (!required) return count;
    const key = `customer.${normalizeId(def)}`;
    return count + (isEmptyValue(answers?.[key], def.type) ? 0 : 1);
  }, 0);

  const customerLayout = layout?.customer?.fields?.length
    ? layout.customer.fields
    : layoutFromDefs(customerDefs);
  const bookingLayout = layout?.booking?.fields?.length
    ? layout.booking.fields
    : layoutFromDefs(bookingDefs);

  function setValue(keyOrNext, val) {
    onChange((prev) => ({ ...prev, [keyOrNext]: val }));
  }

  function getValue(key) {
    return answers?.[key] ?? '';
  }

  function handleNext() {
    const allGroups = [
      { scope: 'customer', defs: customerDefs, layout: customerLayout },
      { scope: 'booking', defs: bookingDefs, layout: bookingLayout },
    ];

    for (const group of allGroups) {
      for (const entry of group.layout) {
        const def = group.defs.find((d) => normalizeId(d) === entry.id);
        if (!def) continue;
        const required = entry.required ?? !!(def.is_required ?? def.required ?? false);
        if (!required) continue;
        const key = `${group.scope}.${entry.id}`;
        const val = getValue(key);
        if (isEmptyValue(val, def.type)) {
          onError?.(`${def.label || entry.id} is required`);
          return;
        }
      }
    }
    onError?.('');
    onNext();
  }

  return (
    <div className="bp-step">
      <div className="bp-step-body">
        <section className="bp-section-card">
          <div className="bp-section-intro">
            <div className="bp-section-eyebrow">Customer details</div>
            <h3 className="bp-section-title">Tell us who this booking is for</h3>
            <p className="bp-section-desc">These details are used to confirm the appointment and send updates.</p>
          </div>
          <div className="bp-customer-trust">
            <div className="bp-customer-trust__status">
              <span className="bp-customer-trust__label">Required details</span>
              <strong>
                {requiredCustomerCount
                  ? `${completedRequiredCustomerCount} of ${requiredCustomerCount} completed`
                  : 'No required customer fields'}
              </strong>
            </div>
            <div className="bp-customer-trust__list">
              <span>Used only for confirmations and updates.</span>
              <span>No account creation required.</span>
              <span>You can review everything before submitting.</span>
            </div>
          </div>
          <DynamicFields
            defs={customerDefs}
            layout={customerLayout}
            values={answers}
            onChange={setValue}
            scope="customer"
          />
        </section>

        {hasBookingSection ? (
          <section className="bp-section-card">
            <div className="bp-section-intro">
              <div className="bp-section-eyebrow">Booking notes</div>
              <h3 className="bp-section-title">Add any appointment-specific information</h3>
              <p className="bp-section-desc">Share anything the team should know before the booking starts. This section is optional unless marked required.</p>
            </div>
            <DynamicFields
              defs={bookingDefs}
              layout={bookingLayout}
              values={answers}
              onChange={setValue}
              scope="booking"
            />
          </section>
        ) : null}
      </div>

      <div className="bp-step-footer">
        <button type="button" className="bp-back" onClick={onBack}>{backLabel}</button>
        <button type="button" className="bp-next" onClick={handleNext}>
          {nextLabel}
        </button>
      </div>
    </div>
  );
}
