'use client';

import AirlineLogo from './AirlineLogo';
import {
  CONTINUE_LABEL,
  REQUEST_APPROVAL_PENDING_LABEL,
} from '@/services/flights/approvalRequest';
import { formatFlightMoney } from '@/services/flights/formatPrice';
import type { RoundTripOption } from '@/services/flights/roundTripPairs';

interface RoundTripPairBarProps {
  /** The chosen outbound. The bar does not appear before there is one. */
  outbound: RoundTripOption;
  /** The chosen return, once there is one. */
  returnOption: RoundTripOption | null;
  /** Back to step 1, keeping the current choice highlighted. */
  onChangeOutbound: () => void;
  /** Forward to fare selection. Only offered once both legs are chosen. */
  onContinue: () => void;
  /** True while the fares modal is being opened, to stop a double submit. */
  isContinuing?: boolean;
}

function LegSummary({ option, label }: { option: RoundTripOption; label: string }) {
  const leg = option.outbound;
  return (
    <div className="round-trip-sticky-item">
      <div className="d-flex align-items-start gap-3">
        <AirlineLogo code={leg.airline.code} name={leg.airline.name} className="round-trip-sticky-logo" />
        <div className="min-w-0">
          <small className="text-xs d-block flight-detail-label fw-600">{label}</small>
          <div className="round-trip-sticky-route d-flex flex-column">
            <span className="color-text-black fw-600 text-sm">
              {leg.departure.time} {leg.departure.airport} — {leg.arrival.time} {leg.arrival.airport}
            </span>
          </div>
          <div className="round-trip-sticky-meta text-xs flight-detail-label">
            {leg.airline.name} · {leg.duration}
            {leg.stops === 0 ? ' · Non-stop' : ` · ${leg.stops} stop${leg.stops === 1 ? '' : 's'}`}
          </div>
        </div>
      </div>
    </div>
  );
}

/**
 * The bar that carries a round-trip choice across the two steps.
 *
 * It shows the trip total straight from the chosen return row, never a sum of
 * the two legs: a pairing's price is the pair's own — sometimes one fare
 * covering both legs, sometimes two added together, and which is cheaper varies
 * per pair. Adding the numbers on screen would produce a third figure matching
 * neither, and it is the one the traveller would be charged that has to be here.
 *
 * On step 1 it appears as soon as an outbound is chosen, so the choice stays
 * visible and changeable while the return list is being read.
 */
export default function RoundTripPairBar({
  outbound,
  returnOption,
  onChangeOutbound,
  onContinue,
  isContinuing = false,
}: RoundTripPairBarProps) {
  const currency = returnOption?.currency ?? outbound.currency;
  // Before a return is chosen, the honest figure is still a "from" — it is the
  // cheapest this outbound can reach, not a price for the trip.
  const total = returnOption?.pricePerPerson ?? outbound.pricePerPerson;
  const isComplete = returnOption !== null;
  // Mirrors the skip-the-modal check RoundTripSearchClient's onContinue makes:
  // when both legs have exactly one fare there is nothing to pick, so this goes
  // straight to the approval request instead of opening the fares modal —
  // "Request approval" says that up front. (leisure-ui booked here instead.)
  const isBookNow =
    isComplete &&
    (outbound.fareOptions?.length ?? 0) === 1 &&
    (returnOption?.fareOptions?.length ?? 0) === 1;

  return (
    <div className="round-trip-sticky-bar js-sticky-bar show" aria-hidden="false">
      <div className="container webNewContent">
        <div className="round-trip-sticky-shell shadow-lg js-sticky-shell flex-column is-collapsed">
          <div className="d-flex align-items-center justify-content-between gap-3 w-100">
            <div className="round-trip-sticky-items js-sticky-items overflow-auto">
              <LegSummary option={outbound} label="Outbound" />
              {returnOption ? (
                <LegSummary option={returnOption} label="Return" />
              ) : (
                <div className="round-trip-sticky-item">
                  <div className="d-flex align-items-start gap-3">
                    <div className="min-w-0">
                      <small className="text-xs d-block flight-detail-label fw-600">Return</small>
                      <span className="text-sm flight-detail-label">Choose your return flight</span>
                    </div>
                  </div>
                </div>
              )}
            </div>

            <div className="round-trip-sticky-summary ms-auto">
              <div className="round-trip-sticky-total">
                <small className="text-xs d-block color-content opacity-75 fw-600">
                  {isComplete ? 'Trip total' : 'From'}
                </small>
                <div className="mainHeading flight-price-amount color-text-black fw-bold mb-0 js-sticky-total">
                  {formatFlightMoney(currency, total)}
                </div>
                <small className="text-xs d-block flight-detail-label">per adult</small>
                {/* Same two figures as the return card's own price block
                    (outbound.pricePerPerson is already the cheapest total for
                    this outbound — see buildReturnOptions/outboundSummary in
                    roundTripPairs.ts — and returnOption.priceDelta is already
                    the gap over it), so the bar and the card the traveller just
                    picked always agree on what the extra cost is. */}
                {isComplete && returnOption && (
                  <small className="text-xs d-block flight-detail-label mt-1">
                    Outbound + cheapest return {formatFlightMoney(currency, outbound.pricePerPerson)} · Return upgrade +{formatFlightMoney(currency, returnOption.priceDelta ?? 0)}
                  </small>
                )}
              </div>
              <div className="d-flex align-items-center gap-2 gap-sm-3">
                <button
                  type="button"
                  className="buttons btnColor-first-outline rounded-3 px-3 py-2 text-sm fw-500"
                  onClick={onChangeOutbound}
                >
                  Change outbound
                </button>
                <button
                  type="button"
                  className="buttons btnColor-second color-text-white-same rounded-3 px-3 py-2 text-sm fw-500"
                  onClick={onContinue}
                  disabled={!isComplete || isContinuing}
                  aria-busy={isContinuing}
                >
                  {isContinuing
                    ? REQUEST_APPROVAL_PENDING_LABEL
                    : isBookNow
                      ? CONTINUE_LABEL
                      : 'Continue'}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
