'use client';

import {
  MAX_CHILDREN_PER_ADULT,
  MAX_SEATED,
  PASSENGER_HINTS,
  clampPassengers,
  passengerLimitNotice,
  type PassengerData,
} from '@/services/flights/passengers';
import { CABIN_LABELS, type CabinClass } from '@/services/flights/searchUrl';

interface CounterRowProps {
  label: string;
  hint: string;
  value: number;
  canDecrement: boolean;
  canIncrement: boolean;
  onStep: (delta: number) => void;
}

function CounterRow({ label, hint, value, canDecrement, canIncrement, onStep }: CounterRowProps) {
  return (
    <div className="fs-counter-row">
      <div className="fs-c-info">
        <div className="fs-c-title">{label}</div>
        <div className="fs-c-sub">{hint}</div>
      </div>
      <div className="fs-stepper">
        <button
          type="button"
          className="fs-step fs-minus"
          disabled={!canDecrement}
          aria-label={`Remove one ${label.toLowerCase().replace(/s$/, '')}`}
          onClick={(e) => {
            e.stopPropagation();
            onStep(-1);
          }}
        >
          −
        </button>
        <span className="fs-num" aria-live="polite">
          {value}
        </span>
        <button
          type="button"
          className="fs-step fs-plus"
          disabled={!canIncrement}
          aria-label={`Add one ${label.toLowerCase().replace(/s$/, '')}`}
          onClick={(e) => {
            e.stopPropagation();
            onStep(1);
          }}
        >
          +
        </button>
      </div>
    </div>
  );
}

interface FlightTravelersV3Props {
  value: PassengerData;
  onChange: (value: PassengerData) => void;
  /**
   * CORP-ONLY (LEIS-934). Pass both to fold cabin class into this panel as
   * "Travellers & Class", the pairing MakeMyTrip uses — which is what frees the
   * column the Booking for field occupies on corp's bar.
   *
   * Optional: without them the panel is exactly the travellers counters it has
   * always been, so a caller that still wants a separate Cabin Class field is
   * unaffected.
   */
  cabinClass?: CabinClass;
  onCabinChange?: (cabin: CabinClass) => void;
}

const CABIN_ORDER: CabinClass[] = ['ECONOMY', 'PREMIUM_ECONOMY', 'BUSINESS', 'FIRST'];

/**
 * The travellers dropdown body. Only the panel — the trigger lives in the form,
 * which renders two of them (a full field on the single-leg row, a compact one
 * in the multi-city control bar) around this same panel.
 *
 * Every "+" that would break a rule is disabled rather than silently clamping,
 * and whichever limit the current selection is sitting on is named underneath:
 * a dead "+" with no explanation is the thing that notice exists to replace.
 */
export default function FlightTravelersV3({
  value,
  onChange,
  cabinClass,
  onCabinChange,
}: FlightTravelersV3Props) {
  const step = (key: keyof PassengerData) => (delta: number) =>
    onChange(clampPassengers({ ...value, [key]: value[key] + delta }));

  const seated = value.adults + value.children;
  const notice = passengerLimitNotice(value);

  return (
    <div className="fs-dropdown fs-traveler-dd" onClick={(e) => e.stopPropagation()}>
      <CounterRow
        label="Adults"
        hint={PASSENGER_HINTS.adults}
        value={value.adults}
        canDecrement={value.adults > 1}
        canIncrement={seated < MAX_SEATED}
        onStep={step('adults')}
      />
      <CounterRow
        label="Children"
        hint={PASSENGER_HINTS.children}
        value={value.children}
        canDecrement={value.children > 0}
        canIncrement={seated < MAX_SEATED && value.children < value.adults * MAX_CHILDREN_PER_ADULT}
        onStep={step('children')}
      />
      <CounterRow
        label="Infants"
        hint={PASSENGER_HINTS.infants}
        value={value.infants}
        canDecrement={value.infants > 0}
        canIncrement={value.infants < value.adults}
        onStep={step('infants')}
      />
      {notice && (
        <p className="fs-traveler-notice" role="status">
          {notice}
        </p>
      )}
      {/* CORP-ONLY: cabin class, folded into this panel. A radiogroup rather
          than a <select> because it sits inside an open popup — a native select
          opens a second layer over this one on mobile, and the four options fit
          on one row anyway. */}
      {cabinClass && onCabinChange ? (
        <div className="fs-cabin-section">
          <div className="fs-cabin-title" id="fs-cabin-label">
            Cabin class
          </div>
          <div className="fs-cabin-chips" role="radiogroup" aria-labelledby="fs-cabin-label">
            {CABIN_ORDER.map((cabin) => (
              <button
                key={cabin}
                type="button"
                role="radio"
                aria-checked={cabinClass === cabin}
                className={`fs-cabin-chip${cabinClass === cabin ? ' is-selected' : ''}`}
                onClick={(e) => {
                  e.stopPropagation();
                  onCabinChange(cabin);
                }}
              >
                {CABIN_LABELS[cabin]}
              </button>
            ))}
          </div>
        </div>
      ) : null}
    </div>
  );
}
