import { Skeleton, SkeletonText } from "@/components/ui/Skeleton";
import FlightStepNav from "./FlightStepNav";
import { useFlightPolicyLimits } from "@/components/flights/FarePolicyBadge";
import { gateFor } from "@/services/employee-requests/fare-policy";
import { airportsFromSegments, parseBookingFor } from "@/services/employee-requests/booking-for";
import { stepIdsFor, stepIndexOf, stepTitlesFor } from "@/services/employee-requests/request-steps";
import {
  parseChildren,
  parseInfants,
  parseItinerary,
} from "@/services/flights/searchUrl";

/**
 * Loading state for the flight review page.
 *
 * Mirrors the geometry of FlightReviewMultiClient closely enough that the swap
 * to real content does not move the page. Two things are rendered for real
 * rather than as grey boxes, because they are already known before the fetch
 * resolves: the step indicator (the step comes from the URL) and the price-lock
 * banner (which already has a "--:--" state for an unknown countdown). Greying
 * out information we actually have would be worse, not more consistent.
 *
 * Repeat counts come from the validated `back` link, see shapeFromBackHref.
 */

/** Amadeus tops out at 9 travellers per booking; the itinerary param allows 2-6 legs. */
const MAX_TRAVELERS = 9;
const MAX_LEGS = 6;

interface SearchShape {
  /** Itinerary blocks to draw on the Review Flight step. */
  legs: number;
  /** Traveller cards to draw on the Traveler Details / Add-ons steps. */
  travelers: number;
}

const DEFAULT_SHAPE: SearchShape = { legs: 1, travelers: 1 };

function clamp(value: number, min: number, max: number): number {
  return Math.min(Math.max(value, min), max);
}

/**
 * Read the repeat counts out of the `back` search link.
 *
 * The real counts live in the response we are still waiting for, but the search
 * the customer came from already implies them: the itinerary param carries the
 * legs, and the passenger params carry the travellers. Using them is what makes
 * this a skeleton of *this* booking rather than a generic one.
 *
 * Parsing is delegated to services/flights/searchUrl.ts, which owns this URL
 * scheme. Everything is clamped: `back` is user-supplied, and safeBackHref
 * validates the path but not the numbers in the query, so `?adults=9999` must
 * not turn into 9999 rendered cards.
 */
function shapeFromBackHref(backHref?: string): SearchShape {
  if (!backHref) return DEFAULT_SHAPE;
  try {
    // safeBackHref guarantees a bare, same-origin path, so the base here is
    // only to satisfy the URL constructor and is never used for anything.
    const params = new URL(backHref, "http://localhost").searchParams;

    const legs = parseItinerary(params.get("itinerary")).length;

    const rawAdults = Number(params.get("adults"));
    const adults = Number.isFinite(rawAdults) && rawAdults > 0 ? Math.floor(rawAdults) : 1;
    // parseChildren reads `children` and still falls back to a legacy `ca=` list,
    // so a `back=` link from before the param change still counts correctly.
    // Lap infants get their own traveller slot in the form, so they count here.
    const travelers = adults + parseChildren(params) + parseInfants(params.get("infants"));

    return {
      legs: legs > 0 ? clamp(legs, 1, MAX_LEGS) : 1,
      travelers: clamp(travelers, 1, MAX_TRAVELERS),
    };
  } catch {
    return DEFAULT_SHAPE;
  }
}

/** A form label over its control — the unit both form steps are built from. */
function FieldSkeleton({
  labelWidth = 90,
  labelHeight = 12,
}: {
  labelWidth?: number | string;
  labelHeight?: number;
}) {
  return (
    <>
      <Skeleton w={labelWidth} h={labelHeight} className="mb-1" />
      <Skeleton h={38} rounded={6} />
    </>
  );
}

/* ── Right column ──────────────────────────────────────────────────────────
   Shared by every step: FlightPriceSummary is the same card throughout, only
   its copy changes. */

function PriceSummarySkeleton() {
  return (
    <div className="shadow-none position-relative h-100">
      {/* No ids anywhere in this file — the real summary uses several, and two
          elements sharing one during a swap is not worth the risk. */}
      <div className="position-sticky top-0">
        <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">
              <Skeleton w={140} h={20} />
            </div>

            {/* Route / Fare Type / Travelers */}
            {[110, 90, 100].map((valueWidth, i) => (
              <div key={i} className="mb-2 px-3">
                <Skeleton w={70} h={11} className="mb-1" />
                <Skeleton w={valueWidth} h={14} />
              </div>
            ))}

            <div className="card-body bgColor-white">
              <div className="d-flex justify-content-between align-items-center py-1">
                <Skeleton w={90} h={14} />
                <Skeleton w={70} h={14} />
              </div>
              <div className="mt-2 border-bottom pb-2 mb-2">
                <Skeleton w={80} h={15} className="mb-2" />
                <Skeleton w="55%" h={11} />
              </div>
              <div className="d-flex justify-content-between align-items-center py-1">
                <Skeleton w={130} h={14} />
                <Skeleton w={70} h={14} />
              </div>
            </div>

            <div className="card-footer bgColor-white pt-1 border-0 border-top">
              <div className="d-flex justify-content-between align-items-center py-1">
                <Skeleton w={150} h={16} />
                <Skeleton w={90} h={18} />
              </div>
              <Skeleton w="85%" h={10} className="mt-2" />
            </div>

            <div className="p-3">
              <Skeleton h={44} rounded={6} className="mt-3" />
              <Skeleton h={44} rounded={6} className="mt-3" />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Step 0 · Review Flight ────────────────────────────────────────────── */

function ItineraryBlockSkeleton() {
  return (
    <div className="p-3 border shadow-sm rounded-3">
      {/* Date + cabin/fare */}
      <div className="d-flex justify-content-between align-items-center gap-3 flex-wrap mb-4">
        <div className="d-flex align-items-center gap-2">
          <Skeleton w={18} h={18} rounded={4} />
          <Skeleton w={150} h={16} />
        </div>
        <Skeleton w={130} h={13} />
      </div>

      <div className="d-flex flex-wrap align-items-start gap-3 mb-4">
        {/* .review-flight-airline-logo is 56px in the live stylesheet. */}
        <Skeleton w={56} h={56} rounded={8} />
        <div className="flex-grow-1">
          <div className="d-flex align-items-center flex-wrap gap-2 mb-2">
            <Skeleton w={140} h={18} />
            <Skeleton w={60} h={14} />
          </div>

          {/* Reuses the real timeline classes so the rail, the 28px indent and
              the 24px item rhythm match exactly; flight-review.css only greys
              the dots, which are green in the live rule. */}
          <div className="flight-timeline">
            <div className="flight-timeline-item dark-green-dot mb-3">
              <div className="pt-1 mb-1 d-flex align-items-center gap-2 flex-wrap">
                <Skeleton w={70} h={20} />
                <Skeleton w={120} h={16} />
              </div>
              <Skeleton w={90} h={11} />
            </div>

            <div className="review-flight-duration rounded-2 d-flex align-items-center gap-2 px-2 py-2 mb-3">
              <Skeleton w={16} h={16} circle />
              <Skeleton w={200} h={11} />
            </div>

            <div className="flight-timeline-item mb-0">
              <div className="pt-1 mb-1 d-flex align-items-center gap-2 flex-wrap">
                <Skeleton w={70} h={20} />
                <Skeleton w={120} h={16} />
              </div>
              <Skeleton w={90} h={11} />
            </div>
          </div>
        </div>
      </div>

      {/* Baggage allowance */}
      <div className="border-top pt-4 mb-2">
        <Skeleton w={220} h={11} className="mb-3" />
        <div className="row g-3">
          {[0, 1].map((i) => (
            <div key={i} className="col-lg-4 col-md-6 col-sm-6 col-12">
              <Skeleton h={38} rounded={8} />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ReviewFlightPaneSkeleton({ legs }: { legs: number }) {
  return (
    <div className="fb-pane">
      <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">
          <Skeleton w={210} h={20} />
        </div>
        <div className="card bgColor-white rounded-3 gap-3 border-0 m-3 mt-0 d-flex flex-column">
          {Array.from({ length: legs }).map((_, i) => (
            <ItineraryBlockSkeleton key={i} />
          ))}
        </div>
      </div>

      {/* Policy accordions — collapsed, so only the header bars show. */}
      <div className="review-flight-accordion mt-4 d-flex flex-column gap-4">
        {[0, 1].map((i) => (
          <div key={i} className="card bgColor-white border-0 rounded-3 shadow-sm">
            <div className="d-flex justify-content-between align-items-center p-3">
              <Skeleton w={180} h={16} />
              <Skeleton w={16} h={16} rounded={4} />
            </div>
          </div>
        ))}
      </div>

      <div className="bgColor-blue-50 border border-color-blue-200 rounded-3 p-3 p-md-4 mt-4">
        <Skeleton w={190} h={18} className="mb-3" />
        <SkeletonText lines={3} lastWidth="45%" />
      </div>
    </div>
  );
}

/* ── Step 1 · Traveler Details ─────────────────────────────────────────── */

function TravelerCardSkeleton() {
  return (
    <div className="traveller-form-wrap rounded-2 mb-3">
      <div className="bgColor-white booking-summary shadow-sm p-3 rounded-3">
        <div className="d-flex align-items-center gap-2 mb-1">
          <Skeleton w={25} h={25} rounded={4} />
          <Skeleton w={150} h={18} />
        </div>
        <Skeleton w={210} h={11} className="mb-3" />

        {/* Title · First name · Last name */}
        <div className="row mb-3">
          <div className="col-md-3">
            <FieldSkeleton labelWidth={45} />
          </div>
          <div className="col-md-3 mt-2 mt-md-0">
            <FieldSkeleton labelWidth={85} />
          </div>
          <div className="col-md-6 mt-2 mt-md-0">
            <FieldSkeleton labelWidth={85} />
          </div>
        </div>

        {/* Date of birth · Gender */}
        <div className="row mb-3">
          <div className="col-md-6">
            <FieldSkeleton labelWidth={95} />
          </div>
          <div className="col-md-6 mt-2 mt-md-0">
            <FieldSkeleton labelWidth={65} />
          </div>
        </div>
      </div>
    </div>
  );
}

function TravelerDetailsPaneSkeleton({ travelers }: { travelers: number }) {
  return (
    <div className="fb-pane">
      <SkeletonText lines={2} lastWidth="40%" className="mb-3" />

      {Array.from({ length: travelers }).map((_, i) => (
        <TravelerCardSkeleton key={i} />
      ))}

      {/* Contact information — always exactly one. */}
      <div className="traveller-form-wrap rounded-2">
        <div className="bgColor-white booking-summary shadow-sm p-3 rounded-3">
          <div className="d-flex align-items-center gap-2 mb-3">
            <Skeleton w={25} h={25} rounded={4} />
            <Skeleton w={190} h={18} />
          </div>
          <SkeletonText lines={2} lastWidth="55%" className="pb-1" />
          <div className="row mt-2">
            <div className="col-md-6">
              <FieldSkeleton labelWidth={110} />
            </div>
            <div className="col-md-6 mt-2 mt-md-0">
              <FieldSkeleton labelWidth={120} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ── Step 2 · Add-ons ──────────────────────────────────────────────────── */

function BagOptionRowSkeleton() {
  return (
    <div className="col">
      {/* Plain border rather than .filter-radio-buttons: that class carries
          :has(:checked) state styling this placeholder should not inherit. */}
      <div className="w-100 rounded-2 border d-flex align-items-center gap-2 p-2">
        <Skeleton w={16} h={16} circle />
        <div className="d-flex justify-content-between align-items-center w-100 gap-2">
          <Skeleton w={140} h={11} />
          <Skeleton w={55} h={11} />
        </div>
      </div>
    </div>
  );
}

function AddOnsPaneSkeleton({ travelers }: { travelers: number }) {
  return (
    <div className="fb-pane">
      <div className="d-flex flex-column gap-3">
        <div>
          <Skeleton w={200} h={20} className="mb-2" />
          <Skeleton w="70%" h={12} />
        </div>

        {Array.from({ length: travelers }).map((_, i) => (
          <div key={i} className="bgColor-white shadow-sm rounded-3 review-flight-card">
            <div className="review-flight-card-header p-3 rounded-3 rounded-bottom-0">
              <Skeleton w={160} h={18} className="mb-2" />
              <Skeleton w={220} h={11} />
            </div>
            <div className="p-3 d-flex flex-column gap-3">
              <div>
                <div className="d-flex align-items-center gap-2 mb-2">
                  <Skeleton w={16} h={16} rounded={4} />
                  <Skeleton w={190} h={14} />
                </div>
                {/* One "no extra bags" row plus a couple of options. Kept small
                    on purpose: addOns.travelers is empty whenever the fare has
                    no purchasable bags, and the pane then collapses to a single
                    short card — a tall guess would overshoot badly. */}
                <div className="row row-cols-1 g-3 mt-1">
                  {[0, 1, 2].map((r) => (
                    <BagOptionRowSkeleton key={r} />
                  ))}
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── Step 3 · Request approval ─────────────────────────────────────────── */
/*
 * corp: leisure-ui's step 3 is Payment — payment-method tiles, a card form and
 * a billing address. None of that exists here; step 3 is Request approval
 * (LEIS-966), and this mirrors PaneRequestApproval's real shape so a cold load
 * of `?step=3` does not jump when the pane arrives.
 *
 * Reachable by more than a hand-typed URL: the flow keeps `?step=` in the
 * address bar, so a reload on the last step lands here. Showing a credit-card
 * form on a screen that never takes a payment was the defect this replaces.
 */
function RequestApprovalPaneSkeleton({ travelers }: { travelers: number }) {
  return (
    <div className="bgColor-white shadow-sm rounded-3 p-3 p-md-4 d-flex flex-column gap-3">
      {/* The navy summary band. Fixed height — it is one row of flight text. */}
      <Skeleton h={88} rounded={12} />

      {/* 1 · Traveller — a two-column grid of read-only rows, one pair per
          passenger-ish. Six fields for the lead traveller, as the pane shows. */}
      <div>
        <Skeleton w={120} h={16} className="mb-3" />
        <div className="row g-3">
          {[0, 1, 2, 3, 4, 5].map((i) => (
            <div key={i} className="col-md-6">
              <Skeleton w={70} h={10} className="mb-1" />
              <Skeleton w="70%" h={14} />
            </div>
          ))}
        </div>
        {travelers > 1 ? <Skeleton w="55%" h={11} className="mt-3" /> : null}
      </div>

      {/* 2 · Business information — client, opportunity, meeting type,
          priority, then the justification textarea and the read-only cost. */}
      <div>
        <Skeleton w={180} h={16} className="mb-3" />
        <div className="row g-3">
          {[0, 1, 2, 3].map((i) => (
            <div key={i} className="col-md-6">
              <FieldSkeleton labelWidth={i % 2 === 0 ? 60 : 95} labelHeight={10} />
            </div>
          ))}
          <div className="col-12">
            <Skeleton w={140} h={10} className="mb-1" />
            <Skeleton h={88} rounded={6} />
          </div>
          <div className="col-md-6">
            <FieldSkeleton labelWidth={100} labelHeight={10} />
          </div>
        </div>
      </div>

      {/* 3 · Travel policy — one row per rule. Three is what the flight tabs
          carry (cabin, maximum fare, booked ahead). */}
      <div>
        <Skeleton w={130} h={16} className="mb-3" />
        <div className="d-flex flex-column gap-2">
          {[0, 1, 2].map((i) => (
            <Skeleton key={i} h={44} rounded={8} />
          ))}
        </div>
      </div>

      {/* Fare, any additional cost, and the total. */}
      <div className="d-flex flex-column gap-2">
        {[0, 1].map((i) => (
          <Skeleton key={i} h={34} rounded={6} />
        ))}
        <SkeletonText lines={1} lineHeight={10} lastWidth="60%" />
      </div>
    </div>
  );
}

/* ── Shell ─────────────────────────────────────────────────────────────── */

function LeftPaneSkeleton({ step, shape }: { step: number; shape: SearchShape }) {
  switch (step) {
    case 1:
      return <TravelerDetailsPaneSkeleton travelers={shape.travelers} />;
    case 2:
      return <AddOnsPaneSkeleton travelers={shape.travelers} />;
    case 3:
      return <RequestApprovalPaneSkeleton travelers={shape.travelers} />;
    default:
      return <ReviewFlightPaneSkeleton legs={shape.legs} />;
  }
}

export default function FlightReviewSkeleton({
  step = 0,
  backHref,
  notice,
}: {
  /** Which step will load — same value the page reads from `?step=`. */
  step?: number;
  /** The validated `back` link: repeat counts, and the route the travel
   *  policy is resolved against. */
  backHref?: string;
  /**
   * Shown instead of the price-lock banner when the wait runs long.
   *
   * It takes that slot rather than adding a row because, while loading, the
   * banner has no countdown to show — the TTL arrives with the response — so
   * it is holding space without carrying information. Reusing the slot means
   * the notice appearing mid-wait moves nothing.
   *
   * aria-hidden: the loader announces this text through its own live region,
   * and announcing it twice helps nobody.
   */
  notice?: string;
}) {
  const shape = shapeFromBackHref(backHref);

  /**
   * The same step list the real screen will draw (LEIS-984).
   *
   * Without this the skeleton would always show four steps and then drop to
   * three the instant the price landed, for every group with Extra baggage
   * switched off — a visible jump in the one element that is meant to stay
   * put while everything else fills in.
   *
   * The route comes from `backHref`, so this is the query key the SRP already
   * populated: on the normal path here it is a cache hit and resolves on the
   * first render. While it is unknown the list keeps Add-ons, so the count can
   * only ever settle downwards, once.
   */
  const backQuery = new URLSearchParams(backHref?.split("?")[1] ?? "");
  const policyLimits = useFlightPolicyLimits({
    travelerId: parseBookingFor(backQuery),
    airports: airportsFromSegments(parseItinerary(backQuery.get("itinerary"))),
  });
  const gate = gateFor(policyLimits);
  const stepIds = stepIdsFor(gate?.extraBaggageAllowed ?? true);
  // Step 4 is "Checkout" for a group that needs no approval — named here too,
  // or the label would flip the instant the price landed.
  const stepTitles = stepTitlesFor(stepIds);
  const stepIndex = stepIndexOf(stepIds, step);

  return (
    <section
      className="py-md-5 py-3 booking-detail-listing-section fr-skeleton"
      // Marks the region as pending. The individual grey boxes are aria-hidden,
      // so this and the loader's live region are all a screen reader sees of it.
      aria-busy="true"
    >
      <div className="container webNewContent travelContent">
        <div className="row">
          <div className="col-12 mb-3">
            <FlightStepNav steps={stepTitles} currentStep={stepIndex} />
          </div>
          <div className="col-12">
            {/* corp: no <PriceLockBanner/> in the else branch. LEIS-963 drops
                the price-lock timer, so the real page never renders one — a
                skeleton that reserves space for a banner that never arrives is
                a layout shift, not a placeholder. The slow-load notice still
                renders here when there is one. */}
            {notice ? (
              <div
                className="bgColor-blue-50 border border-color-blue-200 rounded-3 text-center py-2"
                aria-hidden="true"
              >
                <span className="text-sm color-text-same fw-600">{notice}</span>
              </div>
            ) : null}
          </div>
        </div>

        <div className="row my-3">
          <div className="col-xxl-8 col-xl-8 col-lg-8 col-md-8 col-12">
            <LeftPaneSkeleton step={step} shape={shape} />
          </div>

          <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-4 col-12 mt-3 mt-md-0 d-flex flex-column gap-3">
            <PriceSummarySkeleton />
          </div>
        </div>
      </div>
    </section>
  );
}
