import { Suspense } from "react";
import { redirect } from "next/navigation";
import FlightSearchPanelV3 from "@/components/flights/v3/FlightSearchPanelV3";
import FlightSearchStickyBar from "@/components/flights/FlightSearchStickyBar";
import { BookingForBanner } from "@/components/booking-for/BookingForBanner";
import { BusinessTravelLabel } from "@/components/booking-for/BusinessTravelLabel";
import FlightsSearchClient from "@/components/flights/FlightsSearchClient";
import RoundTripSearchClient from "@/components/flights/RoundTripSearchClient";
import MultiCitySearchClient from "@/components/flights/MultiCitySearchClient";
import BreadcrumbsBar from "@/components/seo/BreadcrumbsBar";
import {
  parseItinerary,
  buildSearchUrl,
  formatDateToYYYYMMDD,
  tripTypeFromParams,
  SRP_FLIGHTS_PATH,
} from "@/services/flights/searchUrl";
import { resolveFlightCityNames } from "@/services/flights/resolveFlightCityNames";
import { resolveDetectedOrigin } from "@/services/flights/defaultOrigin.server";

/**
 * Rendered per request, never prerendered.
 *
 * Same reason as /srp/hotels: leisure-ui's root layout awaits `headers()`,
 * which opts its whole app out of static generation. corp's does not, and this
 * page reads searchParams and redirects, so it must opt out explicitly.
 */
export const dynamic = "force-dynamic";

interface FlightSearchPageProps {
  searchParams: Promise<{ itinerary?: string; tripType?: string }>;
}

/** Ahmedabad -> London, today — this page's default when nobody has searched
 *  anything yet, so a bare visit shows real results instead of an empty
 *  "search for something" prompt. */
const DEFAULT_ITINERARY_ORIGIN = "AMD";
const DEFAULT_ITINERARY_DESTINATION = "LHR";

/**
 * The one flight SRP, for all three trip types.
 *
 * Trip type is `tripType` in the query rather than a path segment. It used to
 * be a path — /srp/flights/round-trip, /srp/flights/multi-city — which made
 * switching it a navigation between two different client components, so the
 * results on screen could never simply refresh in place. Those paths still
 * resolve; they redirect here.
 *
 * Each trip type keeps the cold-start behaviour its own route had, because they
 * genuinely differ: one-way sends a bare visit to a real default itinerary so
 * the page always opens on live results, while the other two resolve the
 * visitor's likely origin and let the form ask for the rest.
 */
export default async function FlightSearchPage({ searchParams }: FlightSearchPageProps) {
  const params = await searchParams;
  const reader = {
    get: (name: string) => (params as Record<string, string | undefined>)[name] ?? null,
  };
  const tripType = tripTypeFromParams(reader);
  const segments = parseItinerary(params.itinerary ?? null);

  // Nothing to search for yet — redirect once to a real default itinerary so
  // this page always lands on live results, not FlightsSearchClient's
  // NO_SEARCH_YET empty state. A URL that already names an itinerary (even a
  // stale/past-date one, which parseItinerary itself clamps) is left alone.
  if (tripType === "oneway" && segments.length === 0) {
    const qs = buildSearchUrl({
      tripType: "oneway",
      origin: DEFAULT_ITINERARY_ORIGIN,
      destination: DEFAULT_ITINERARY_DESTINATION,
      departDate: formatDateToYYYYMMDD(new Date()),
      adults: 1,
      infants: 0,
      cabinClass: "ECONOMY",
      directOnly: false,
    });
    redirect(`${SRP_FLIGHTS_PATH}?${qs}`);
  }

  const codes = Array.from(new Set(segments.flatMap((s) => [s.from, s.to])));
  const initialLocationNames = codes.length ? await resolveFlightCityNames(codes) : {};

  // Cold path only: an itinerary in the URL already states the origin, so a real
  // search costs no IP or airport lookup at all.
  const detectedOrigin = segments.length ? null : await resolveDetectedOrigin();

  return (
    <>
      <BreadcrumbsBar />
      <FlightSearchPanelV3
        initialLocationNames={initialLocationNames}
        initialOrigin={detectedOrigin?.origin}
        initialOriginCountry={detectedOrigin?.countryCode}
      />
      <FlightSearchStickyBar initialLocationNames={initialLocationNames} />
      {/* CORP-ONLY (LEIS-983): "Business travel", plus "needs approval" when
          the traveller's group requires it for this tab. Renders nothing until
          the gate is known. */}
      <BusinessTravelLabel />
      {/* CORP-ONLY (LEIS-934): says whose trip this is whenever it is not the
          signed-in employee's. Renders nothing otherwise. */}
      <BookingForBanner />
      <section className="my-md-5 flight-list my-4">
        <div className="webNewContent container">
          <Suspense
            fallback={
              <div
                className="d-flex justify-content-center align-items-center"
                style={{ minHeight: 400 }}
              >
                <div className="spinner-border text-primary" role="status">
                  <span className="visually-hidden">Loading...</span>
                </div>
              </div>
            }
          >
            {/*
              Keyed by trip type so switching genuinely remounts the results
              client. The three hold different local state — a round-trip
              outbound selection, a multi-city leg cursor — and React would
              otherwise reuse the mounted tree for whichever component happens
              to land in the same position.
            */}
            {tripType === "roundtrip" ? (
              <RoundTripSearchClient key="roundtrip" initialLocationNames={initialLocationNames} />
            ) : tripType === "multicity" ? (
              <MultiCitySearchClient key="multicity" initialLocationNames={initialLocationNames} />
            ) : (
              <FlightsSearchClient key="oneway" initialLocationNames={initialLocationNames} />
            )}
          </Suspense>
        </div>
      </section>
    </>
  );
}
