"use client";

import { useEffect, useRef, useState, type ReactNode } from "react";
import FlightReviewMultiClient from "./FlightReviewMultiClient";
import FlightReviewUnavailable from "./FlightReviewUnavailable";
import FlightReviewSkeleton from "./FlightReviewSkeleton";
import {
  buildFlightError,
  flightErrorFromException,
  parseFlightError,
  type FlightError,
} from "@/services/flights/errors";
import { mapFlightPriceToReviewView } from "@/services/flights/mapper";
import type { FlightPriceResponseData, FlightReviewViewModel } from "@/services/flights/types";

/**
 * Floor on how long the skeleton stays up.
 *
 * Without it a fast answer — in practice a cached failure, since a live Amadeus
 * price is never this quick — paints the skeleton for a few frames and rips it
 * away, which reads as a glitch rather than as loading. The cost is up to 300ms
 * added to an already-failed request, which is below the threshold where a
 * delay is noticed at all; the flicker is not.
 */
const MIN_SKELETON_MS = 300;

/**
 * When to admit the wait is long. Price #1 is a live Amadeus call with a 20s
 * upstream timeout, and going silent for that long on the screen before payment
 * reads as a hung page.
 */
const SLOW_NOTICE_MS = 6000;

const LOADING_MESSAGE = "Loading your flight details…";
const SLOW_MESSAGE = "Still confirming the live fare with the airline…";
/** Announced on completion — without it, a wait this long simply goes quiet. */
const READY_MESSAGE = "Flight details loaded.";

type LoadState =
  | { status: "loading" }
  | { status: "ready"; review: FlightReviewViewModel }
  | { status: "error"; error: FlightError };

/**
 * One-shot fetch of Price #1 for a clientRef. Never rejects — always resolves to
 * a LoadState so the effect below needs no try/catch or unhandled-rejection guard.
 */
async function loadFlightReview(clientRef: string): Promise<LoadState> {
  try {
    const res = await fetch(`/api/flights/reviews?clientRef=${encodeURIComponent(clientRef)}`, {
      method: "GET",
      headers: { Accept: "application/json", "Cache-Control": "no-store" },
      cache: "no-store",
    });
    const json = (await res.json().catch(() => ({}))) as {
      success?: boolean;
      data?: FlightPriceResponseData;
      message?: string;
      error?: string;
    };
    if (!res.ok || json.success === false || !json.data) {
      // Note the 200-with-success:false case: this endpoint can answer OK and
      // still report failure in the body, so res.ok alone is not enough.
      return { status: "error", error: await parseFlightError(res, json) };
    }
    return { status: "ready", review: mapFlightPriceToReviewView(json.data) };
  } catch (err) {
    // An aborted load is not a failure, but this fetch has no signal, so
    // flightErrorFromException can only return null if something else aborts it.
    return {
      status: "error",
      error: flightErrorFromException(err) ?? buildFlightError("UNKNOWN"),
    };
  }
}

/**
 * Client-side loader for the flight review (Price #1). Fetches through the
 * same-origin /api/flights/reviews proxy (see that route for why a direct
 * browser call to search-service is the wrong shape here — NEXT_PUBLIC_*
 * build-time inlining, not an SSR network issue). Runs in the browser so
 * the page shell can paint immediately instead of the whole route blocking
 * on a server fetch that has no timeout.
 *
 * The request promise is cached on a ref so React 18 Strict Mode's double
 * effect-invoke reuses one request rather than firing — and then cancelling —
 * two. A different clientRef remounts the whole component (key in page.tsx), so
 * the ref and `loading` state reset without a setState-in-effect.
 */
export default function FlightReviewLoader({
  clientRef,
  initialStep = 0,
  backHref,
  bookingFor = null,
}: {
  clientRef: string;
  initialStep?: number;
  /** Already validated by the page — where "search again" goes. */
  backHref?: string;
  /**
   * corp: the colleague this request is for, or null for the employee
   * themselves (LEIS-934). Validated by the page; threaded through because
   * step 2 fills from that person's profile and step 4 is judged against
   * their group's policy. leisure-ui has no such concept.
   */
  bookingFor?: string | null;
}) {
  const [state, setState] = useState<LoadState>({ status: "loading" });
  const [isSlow, setIsSlow] = useState(false);
  const promiseRef = useRef<Promise<LoadState> | null>(null);

  useEffect(() => {
    let ignore = false;
    if (!promiseRef.current) {
      promiseRef.current = loadFlightReview(clientRef);
    }

    // Race the request against a floor rather than delaying the setState by a
    // fixed amount: a request slower than the floor — the normal case — is not
    // held up at all. Strict Mode's second pass makes a second timer here, but
    // the request itself is still the one cached on promiseRef.
    Promise.all([
      promiseRef.current,
      new Promise((resolve) => setTimeout(resolve, MIN_SKELETON_MS)),
    ]).then(([result]) => {
      if (!ignore) setState(result);
    });

    const slowTimer = setTimeout(() => {
      if (!ignore) setIsSlow(true);
    }, SLOW_NOTICE_MS);

    return () => {
      ignore = true;
      clearTimeout(slowTimer);
    };
  }, [clientRef]);

  // Errors say nothing here: FlightReviewUnavailable renders its own heading and
  // copy, and announcing the failure twice is worse than announcing it once.
  const statusMessage =
    state.status === "loading"
      ? isSlow
        ? SLOW_MESSAGE
        : LOADING_MESSAGE
      : state.status === "ready"
        ? READY_MESSAGE
        : "";

  let body: ReactNode;
  if (state.status === "loading") {
    body = (
      <FlightReviewSkeleton
        step={initialStep}
        backHref={backHref}
        notice={isSlow ? SLOW_MESSAGE : undefined}
      />
    );
  } else if (state.status === "error") {
    body = (
      <FlightReviewUnavailable
        error={state.error}
        backHref={backHref}
        reference={clientRef}
      />
    );
  } else {
    body = (
      <FlightReviewMultiClient
        review={state.review}
        initialStep={initialStep}
        backHref={backHref}
        bookingFor={bookingFor}
      />
    );
  }

  // One live region for the whole lifecycle, kept in a fixed position ahead of
  // the body so React reuses the same DOM node across the swap. That node
  // identity is the point: a region that unmounts with the skeleton can only
  // announce the wait, never the end of it, and a multi-second wait that
  // finishes in silence leaves a screen-reader user with nothing to act on.
  return (
    <>
      <div role="status" aria-live="polite" className="visually-hidden">
        {statusMessage}
      </div>
      {body}
    </>
  );
}
