import type { FlightItineraryView, FlightPolicies, FlightReviewViewModel } from '@/services/flights/types';
import { ItineraryHeader, LegPanel } from '@/components/flights/FlightItinerary';
import { buildRouteSummaryPayload, type FlightRouteSummaryPayload } from '@/services/flights/buildRouteSummaryPayload';
import { openRouteSummaryAssistant } from '@/components/chat/chat-events';

/**
 * Same per-segment/layover card the search-results page shows for this
 * flight (ItineraryHeader + LegPanel from components/flights/FlightItinerary),
 * fed by itin.legDetail — built server-response-side in
 * services/flights/mapper.ts via the same buildLegItinerary the search
 * pipeline uses. Keeps this screen and the search card from drifting apart
 * the way the old bespoke ItineraryBlock had (raw aircraft codes, "T2"
 * terminals, first/last-segment-only display).
 */
/**
 * Scope key for one itinerary on this page.
 *
 * The review page has no `sliceKeys`: it renders a priced offer, not a search
 * result, and Flight Offers Pricing does not carry search-service's slice keys
 * through. It does not need them either — a slice key exists so a flight can be
 * named across *different responses*, and this page shows exactly one offer,
 * pinned by the `clientRef` in its own URL. Uniqueness within the page is all
 * the fragment requires, and that is what the itinerary's own label, flight
 * number and position give — the same recipe the React key below already
 * trusts.
 *
 * Prefixed so it can never be mistaken for, or collide with, a real slice key.
 */
function reviewLegKey(itin: FlightItineraryView, index: number): string {
  return `review:${itin.label}:${itin.flightNumber}:${index}`;
}

function ItineraryBlock({
  itin,
  index,
  routePayload,
  siblingPayload,
}: {
  itin: FlightItineraryView;
  index: number;
  routePayload?: FlightRouteSummaryPayload;
  siblingPayload?: FlightRouteSummaryPayload;
}) {
  const leg = itin.legDetail;
  if (!leg || leg.segments.length === 0) return null;

  const first = leg.segments[0];
  const last = leg.segments[leg.segments.length - 1];
  const title = `${first.departure.city} → ${last.arrival.city}`;

  return (
    <div className="p-3 border shadow-sm rounded-3">
      <ItineraryHeader
        leg={leg}
        title={title}
        date={first.departure.date}
        totalDuration={itin.durationLabel}
        refundStatus={itin.refundStatus}
        hasFareRules={false}
        onOpenFareRules={() => {}}
      />
      <LegPanel
        leg={leg}
        cabinClass={itin.cabinLabel || 'Economy'}
        sliceKey={reviewLegKey(itin, index)}
      />
      {routePayload && (
        <button
          type="button"
          className="flight-summary-cta border-0 bg-transparent text-sm fw-600 mt-3 d-inline-flex align-items-center gap-1"
          onClick={() =>
            openRouteSummaryAssistant(
              routePayload,
              siblingPayload,
              `Summarize my ${routePayload.originCity} → ${routePayload.destinationCity} flight on ${routePayload.dateLabel}`,
            )
          }
        >
          ✨ Need a summary? Just ask Assistant ›
        </button>
      )}
    </div>
  );
}

export default function ReviewFlightCard({
  review,
  nested = false,
}: {
  review: FlightReviewViewModel;
  nested?: boolean;
}) {
  const inner = (
    <>
      <div className="card bgColor-white border-0 rounded-3 shadow-sm review-flight-card">
        <div className="d-flex flex-wrap justify-content-between align-items-center gap-2 p-3 rounded-3 rounded-bottom-0">
          {/* corp: "Review your request", not leisure-ui's "Complete your
              booking". Nothing is booked from this flow — the employee is
              assembling a request a company admin will approve, and only then
              is anything bought (PRD §9.1). Promising a booking on step 1 of
              four would misdescribe the whole screen. */}
          <h3 className="subHeading mb-0 text-uppercase fw-bold">Review your request</h3>
        </div>

        <div className="card bgColor-white rounded-3 gap-3 border-0 m-3 mt-0 d-flex flex-column">
          {(review.itineraries || []).map((itin, idx, all) => {
            // A sibling only exists for a round trip's two legs — multi-city's
            // "summarize leg N" behavior isn't specified by the ticket, so no
            // sibling (and no return-leg chip) is offered there.
            const siblingIdx = all.length === 2 ? (idx === 0 ? 1 : 0) : undefined;
            const routePayload = buildRouteSummaryPayload(itin, idx, review.policies, siblingIdx !== undefined);
            const siblingPayload =
              siblingIdx !== undefined
                ? buildRouteSummaryPayload(all[siblingIdx], siblingIdx, review.policies, true)
                : undefined;
            return (
              <ItineraryBlock
                key={`${itin.label}-${itin.flightNumber}-${idx}`}
                itin={itin}
                index={idx}
                routePayload={routePayload}
                siblingPayload={siblingPayload}
              />
            );
          })}
        </div>
      </div>
    </>
  );

  if (nested) return inner;

  return (
    <div
      className="fb-pane"
      data-step-title="Price Breakup"
      data-next-label="Continue with Travel Details"
      data-total-label="Total Amount to be paid"
      data-footer-note="By continuing, you agree to our Terms &amp; Conditions"
    >
      {inner}
    </div>
  );
}
