import type {
  FlightPassengerBreakdown,
  FlightPriceLine,
  FlightReviewViewModel,
} from '@/services/flights/types';
import { travelerTypeLabel } from '@/services/flights/travelers';

/** A row whose amount is exactly zero carries no information; "0.00" passengers are the deliberate exception. */
function isZero(amount: string): boolean {
  return Number.parseFloat(amount || '0') === 0;
}

function Money({ symbol, amount }: { symbol: string; amount: string }) {
  return (
    <span className="text-nowrap">
      {symbol}
      {amount}
    </span>
  );
}

/** Add-on / fee / discount line: label left, amount right. */
function SummaryLine({
  label,
  amount,
  symbol,
  negative = false,
  bold = false,
}: {
  label: string;
  amount: string;
  symbol: string;
  negative?: boolean;
  bold?: boolean;
}) {
  return (
    <div className="d-flex justify-content-between align-items-baseline gap-2 py-1">
      <span className={`text-sm ${bold ? 'fw-600' : ''} color-text-same`}>{label}</span>
      <span
        className={`text-sm ${bold ? 'fw-600' : ''} ${negative ? 'color-text-green-700' : 'color-text-same'}`}
      >
        {negative ? '-' : ''}
        <Money symbol={symbol} amount={amount} />
      </span>
    </div>
  );
}

/**
 * One passenger type at one price: the bold "Adult  $1,625.49 x 2" row, with
 * base fare and taxes beneath it.
 *
 * Every amount here is per ONE passenger and covers the whole trip — legs are
 * already summed by search-service. `count` is the multiplier, not a divisor,
 * which is why the label stays singular ("Adult x 2", not "Adults").
 */
function PassengerGroupRow({
  group,
  symbol,
}: {
  group: FlightPassengerBreakdown['groups'][number];
  symbol: string;
}) {
  return (
    <div className="mb-3">
      <div className="d-flex justify-content-between align-items-baseline gap-2">
        <span className="text-sm fw-700 color-text-dark">
          {travelerTypeLabel(group.travelerType)}
        </span>
        <span className="text-sm fw-700 color-text-dark">
          <Money symbol={symbol} amount={group.unitTotal} />
          <span className="fw-400 color-text-gray ms-1">x {group.count}</span>
        </span>
      </div>

      <div className="d-flex justify-content-between align-items-baseline gap-2 mt-1">
        <span className="text-xs color-text-gray">Base fare</span>
        <span className="text-xs color-text-gray">
          <Money symbol={symbol} amount={group.unitBase} />
        </span>
      </div>

      <div className="d-flex justify-content-between align-items-baseline gap-2">
        <span className="text-xs color-text-gray">Taxes and fees</span>
        <span className="text-xs color-text-gray">
          <Money symbol={symbol} amount={group.unitTaxes} />
        </span>
      </div>
    </div>
  );
}

/**
 * Agoda-style price breakdown.
 *
 * The rows reconcile to the total by construction:
 *   sum(groupTotal) + addOns + fees + margins - discounts + residual = grandTotal
 * search-service owns that arithmetic. Nothing here re-sums it — the Total is
 * rendered from `review.grandTotal`, which can legitimately differ from the
 * visible rows by a cent through rounding.
 */
function PriceBreakdown({
  breakdown,
  symbol,
}: {
  breakdown: FlightPassengerBreakdown;
  symbol: string;
}) {
  const extras: Array<FlightPriceLine & { negative?: boolean }> = [
    ...breakdown.addOns,
    ...breakdown.fees,
    ...breakdown.margins,
    ...breakdown.discounts.map((line) => ({ ...line, negative: true })),
  ].filter((line) => !isZero(line.amount));

  // Non-zero means search-service found money it could not attribute to any
  // known field. Showing it keeps the rows visibly adding up rather than
  // leaving a silent gap on a payment screen; it is logged server-side too.
  const hasResidual = !isZero(breakdown.residual);

  return (
    <>
      <h4 className="text-md fw-700 color-text-dark mb-2">Price breakdown</h4>

      {breakdown.groups.map((group, i) => (
        <PassengerGroupRow
          key={`${group.travelerType}-${group.unitTotal}-${i}`}
          group={group}
          symbol={symbol}
        />
      ))}

      {extras.length > 0 || hasResidual ? (
        <div className="border-top pt-2 mt-2">
          {extras.map((line, i) => (
            <SummaryLine
              key={`${line.label}-${i}`}
              label={line.label}
              amount={line.amount}
              symbol={symbol}
              negative={line.negative}
            />
          ))}
          {hasResidual ? (
            <SummaryLine label="Other charges" amount={breakdown.residual} symbol={symbol} />
          ) : null}
        </div>
      ) : null}
    </>
  );
}

/**
 * Pre-breakdown totals. Still needed: search-service omits passengerBreakdown
 * when it cannot build one safely (legs pricing different traveler sets), and
 * older deployments do not send it at all.
 */
function LegacyTotals({ review }: { review: FlightReviewViewModel }) {
  const hasTaxRow =
    !!review.taxesTotal || review.taxLines.length > 0 || review.feeLines.length > 0;

  return (
    <>
      {review.base ? (
        <ul className="d-flex justify-content-between passenger-price-summary ps-0 py-1 mb-0">
          <li className="passenger-number text-sm">
            Base Price
            <br />
            {review.travelerLabel ? <small>[ {review.travelerLabel} ]</small> : null}
          </li>
          <li className="passenger-fare text-sm text-end">
            {review.currencySymbol} {review.base}
          </li>
        </ul>
      ) : null}

      {hasTaxRow ? (
        <ul className="d-flex justify-content-between passenger-price-summary ps-0 py-1 mb-0">
          <li className="passenger-number text-sm">Taxes &amp; Service Fees</li>
          {/* Taxes AND fees are listed above, so the row total must cover both —
              heading a taxes+fees list with a taxes-only amount is what made the
              old summary fail to add up to the total. */}
          <li className="passenger-fare text-sm text-right">
            {review.currencySymbol}{' '}
            {(
              Number.parseFloat(review.taxesTotal || '0') +
              Number.parseFloat(review.feesTotal || '0')
            ).toFixed(2)}
          </li>
        </ul>
      ) : null}
    </>
  );
}

export default function FlightPriceSummary({
  review,
  nextLabel = 'Continue with Travel Details',
  footerNote = 'By continuing, you agree to our Terms & Conditions',
  stepTitle = 'Price Breakup',
  totalLabel = 'Total Amount to be paid',
  prevDisabled = false,
  nextDisabled = false,
  priceNote,
  onPrev,
  onNext,
  /** LEIS-1010: shown directly below Continue/Submit, not as a separate
   *  block under the form — the employee's two options for the last step
   *  belong together in the one place that already drives the step. */
  showBookNow = false,
  bookNowPending = false,
  onBookNow,
  /** LEIS-1004: the Submit/Continue button is meaningless at the final step
   *  for an admin — "Request approval" would file a request in their OWN
   *  approval queue, which the server already refuses outright, so there is
   *  nothing for this button to do there but fail. Book Now is their only
   *  real action at that step; everywhere else (steps 1-3) this stays false
   *  and Next/Continue works exactly as it does for an employee. */
  hideNext = false,
  /** Overrides the line under Book Now — the default copy talks about "your
   *  group," which doesn't mean anything for an admin booking company-wide. */
  bookNowNote = "Your group doesn't require approval for this trip — pay now and skip the wait.",
}: {
  review?: FlightReviewViewModel;
  nextLabel?: string;
  footerNote?: string;
  stepTitle?: string;
  totalLabel?: string;
  /**
   * Disables Back. Used for the first step, which has nowhere to go, and while
   * an operation started from this footer is still running — walking out of a
   * payment mid-charge is the one thing this screen must not allow.
   */
  prevDisabled?: boolean;
  nextDisabled?: boolean;
  /** Small line under the total, e.g. "Updating price…" / "Estimated — confirmed at checkout". */
  priceNote?: string;
  onPrev?: () => void;
  onNext?: () => void;
  showBookNow?: boolean;
  bookNowPending?: boolean;
  onBookNow?: () => void;
  hideNext?: boolean;
  bookNowNote?: string;
}) {
  if (!review) return null;

  const breakdown = review.passengerBreakdown;

  return (
    <div className="shadow-none position-relative h-100 sticky-payment-summary">
      <div className="accordion position-sticky top-0" id="priceSummary">
        <div className="booking-summary">
          <div className="booking-details card bgColor-white border-0 rounded-3 shadow-sm p-0">
            <div className="card-header pt-3 bgColor-white border-0">
              <h3 className="subHeading mb-0 text-lg fw-bold" id="summaryStepTitle">
                {stepTitle}
              </h3>
            </div>
            {review.routeLabel ? (
              <div className="mb-2 px-3">
                <span className="text-muted d-block text-sm">Route</span>
                <span className="fw-semibold d-block font-inter text-sm color-text-dark">
                  {review.routeLabel}
                </span>
              </div>
            ) : null}
            {review.fareType ? (
              <div className="mb-2 px-3">
                <span className="text-muted d-block text-sm">Fare Type</span>
                <span className="fw-semibold d-block font-inter text-sm color-text-dark">
                  {review.fareType}
                </span>
              </div>
            ) : null}
            {review.travelerLabel ? (
              <div className="px-3">
                <span className="text-muted d-block text-sm">Travelers</span>
                <span className="fw-semibold d-block font-inter text-sm color-text-dark">
                  {review.travelerLabel}
                </span>
              </div>
            ) : null}

            <div className="card-body bgColor-white">
              {breakdown ? (
                <PriceBreakdown breakdown={breakdown} symbol={review.currencySymbol} />
              ) : (
                <LegacyTotals review={review} />
              )}
            </div>

            <div className="card-footer bgColor-white pt-1 border-0 border-top">
              <ul className="d-flex justify-content-between passenger-price-summary passenger-price-summary-total ps-0 py-1 mb-0">
                <li className="passenger-number text-md fw-semibold" id="summaryTotalLabel">
                  {totalLabel}
                </li>
                <li className="passenger-fare text-md text-right fw-semibold">
                  {review.currencySymbol}
                  {review.grandTotal}
                </li>
              </ul>
              {priceNote ? (
                <small className="text-xs color-text-second d-block fw-600">{priceNote}</small>
              ) : null}
              <small className="text-xs">
                Including all taxes, fees, surcharges and leisure.com service fees
              </small>
            </div>
            <div className="p-3">
              <button
                type="button"
                className="buttons btnColor-first rounded-2 mt-3 w-100 text-md"
                disabled={prevDisabled}
                onClick={onPrev}
              >
                Back
              </button>
              {!hideNext && (
                <button
                  type="button"
                  className="buttons btnColor-second rounded-2 mt-3 w-100 text-md"
                  disabled={nextDisabled}
                  onClick={onNext}
                >
                  {nextDisabled ? 'Confirming…' : nextLabel}
                </button>
              )}
              {showBookNow && (
                <>
                  <button
                    type="button"
                    className="buttons btnColor-second rounded-2 mt-3 w-100 text-md"
                    disabled={bookNowPending}
                    onClick={onBookNow}
                  >
                    <i className="bi bi-wallet2 me-2" aria-hidden="true" />
                    {bookNowPending ? 'Please wait…' : 'Book Now'}
                  </button>
                  <small className="text-xs d-block mt-2">{bookNowNote}</small>
                </>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
