import React, { useMemo } from 'react';

export default function StepReview({
  locationId,
  categoryIds,
  serviceId,
  extraIds,
  agentId,
  date,
  slot,
  locations,
  categories,
  services,
  extras,
  agents,
  formFields,
  answers,
  paymentMethodLabel,
  totalLabel,
  showLocation = true,
  showExtras = true,
  showPayment = true,
  hasPayment = false,
  onBack,
  onNext,
  isCreatingBooking,
  createError,
  loading,
  backLabel = '<- Back',
  nextLabel = 'Next ->',
}) {
  const loc = locations.find((x) => String(x.id) === String(locationId));
  const svc = services.find((x) => String(x.id) === String(serviceId));
  const ag = agents.find((x) => String(x.id) === String(agentId));
  const cats = categories.filter((x) => categoryIds.includes(x.id) || categoryIds.includes(String(x.id)));
  const ex = extras.filter((x) => extraIds.includes(x.id) || extraIds.includes(String(x.id)));

  const fields = useMemo(() => ([
    ...(formFields?.form || []),
    ...(formFields?.customer || []),
    ...(formFields?.booking || []),
  ]), [formFields]);
  const isBusy = !!loading || !!isCreatingBooking;
  const nextHeading = hasPayment ? 'What happens next' : 'Ready to confirm';
  const nextDescription = hasPayment
    ? `You will continue to ${paymentMethodLabel || 'your selected payment method'} on the next step.`
    : 'Submitting now will create the booking immediately and send the confirmation details.';
  const nextChecklist = hasPayment
    ? [
      'Secure payment details are handled on the next step.',
      'Your time stays reviewable before payment is finalized.',
      'Confirmation is sent using the contact details above.',
    ]
    : [
      'The appointment will be created immediately.',
      'Confirmation is sent using the contact details above.',
      'You can go back now if anything needs to change.',
    ];

  return (
    <div className="bp-step">
      <div className="bp-step-body">
        <div className="bp-review-layout">
          <section className="bp-section-card bp-section-card--review">
            <div className="bp-section-intro">
              <div className="bp-section-eyebrow">Booking summary</div>
              <h3 className="bp-section-title">Review the appointment details</h3>
              <p className="bp-section-desc">Check the service, schedule, and total before you continue.</p>
            </div>
            <div className="bp-review">
              {showLocation ? <ReviewRow label="Location" value={loc?.name} /> : null}
              <ReviewRow label="Categories" value={cats.length ? cats.map((c) => c.name).join(', ') : '-'} />
              <ReviewRow label="Service" value={svc?.name} />
              <ReviewRow label="Agent" value={ag?.name} />
              <ReviewRow label="Date" value={date} />
              <ReviewRow label="Time" value={slot?.start_time ? `${slot.start_time} - ${slot.end_time}` : '-'} />
              {showExtras ? <ReviewRow label="Extras" value={ex.length ? ex.map((e) => e.name).join(', ') : '-'} /> : null}
              {showPayment && paymentMethodLabel ? <ReviewRow label="Payment Method" value={paymentMethodLabel} /> : null}
              {totalLabel ? <ReviewRow label="Total" value={totalLabel} /> : null}
            </div>
          </section>

          <section className="bp-section-card bp-section-card--review">
            <div className="bp-section-intro">
              <div className="bp-section-eyebrow">Contact details</div>
              <h3 className="bp-section-title">Confirm contact and booking notes</h3>
              <p className="bp-section-desc">Make sure the confirmation details are accurate before submitting.</p>
            </div>
            <div className="bp-review">
              {fields.length ? fields.map((f) => {
                const fieldKey = f.field_key || f.name_key || '';
                const key = `${f.scope}.${fieldKey}`;
                const v = formatReviewValue(answers?.[key], f.type);
                return <ReviewRow key={key} label={f.label} value={v} />;
              }) : <ReviewRow label="Details" value="No additional information required." />}
            </div>
          </section>
        </div>

        <section className="bp-section-card bp-section-card--review">
          <div className="bp-section-intro">
            <div className="bp-section-eyebrow">Next step</div>
            <h3 className="bp-section-title">{nextHeading}</h3>
            <p className="bp-section-desc">{nextDescription}</p>
          </div>
          <div className="bp-review-callout">
            {totalLabel ? (
              <div className="bp-review-callout__amount">
                <span>Total due</span>
                <strong>{totalLabel}</strong>
              </div>
            ) : null}
            <div className="bp-checklist">
              {nextChecklist.map((item) => (
                <div key={item} className="bp-checklist__item">{item}</div>
              ))}
            </div>
          </div>
        </section>

        {createError ? (
          <div className="bp-alert bp-alert-error bp-mt-12">
            {createError}
          </div>
        ) : null}
      </div>

      <div className="bp-step-footer">
        <button type="button" className="bp-back" onClick={onBack}>{backLabel}</button>
        <button type="button" className="bp-next" disabled={isBusy} onClick={onNext}>
          {isCreatingBooking ? (hasPayment ? 'Preparing payment...' : 'Booking...') : loading ? 'Submitting...' : nextLabel}
        </button>
      </div>
    </div>
  );
}

function ReviewRow({ label, value }) {
  return (
    <div className="bp-review-row">
      <div className="k">{label}</div>
      <div className="v">{value || '-'}</div>
    </div>
  );
}

function formatReviewValue(value, type) {
  if (type === 'checkbox') {
    return value === true || value === 1 || value === '1' ? 'Yes' : 'No';
  }
  if (Array.isArray(value)) {
    return value.length ? value.join(', ') : '-';
  }
  if (value == null) return '-';
  const text = String(value).trim();
  return text || '-';
}
