"use client";

import { useEffect, useRef } from "react";
import { useRouter, useSearchParams } from "next/navigation";

import {
  subscribeToApprovalRequests,
  type ApprovalRequestEvent,
} from "@/services/employee-requests/approval-bus";
import { parseBookingFor } from "@/services/employee-requests/booking-for";
import { createFlightReview } from "@/services/flights/flight-reviews.client";
import { getFlightReviewPageHref } from "@/services/flights/flight-reviews.api";
import { toast } from "@/lib/toast";
import { logger } from "@/lib/logger";

/**
 * Takes every "Request approval" press on the SRP into the 4-step request flow.
 *
 * Mounted once in app/srp/layout.tsx so all four result surfaces — the card,
 * the fares modal, the round-trip pair bar, the multi-city bar — go through one
 * place. See services/employee-requests/approval-bus.ts for why it is wired
 * through an emitter rather than a context.
 *
 * ── It used to open a dialog ────────────────────────────────────────────────
 *
 * Until LEIS-961 this host rendered <RequestApprovalModal/>: picking a flight
 * opened the E4 overlay and the employee filled the whole request in there.
 * Flights now go through Review Flight → Traveler Details → Add-ons → Request
 * approval instead, so this navigates rather than opens.
 *
 * **The overlay is not dead.** LEIS-966 keeps it for hotels, which have no
 * stepper yet. It is simply no longer reachable from the flights SRP.
 *
 * ── Why the navigation happens here ─────────────────────────────────────────
 *
 * The four surfaces are ported files kept byte-identical against leisure-ui.
 * They call `requestFlightApproval()` and await a boolean — a shape that cannot
 * mint a review, read the query string or push a route. This host can do all
 * three, so none of them needed editing, which is the same reason the bus
 * exists at all.
 */
export function RequestApprovalHost() {
  const router = useRouter();
  /**
   * Who the trip is for, read from the URL rather than carried on the bus
   * (LEIS-934).
   *
   * The bus carries what those four ported surfaces know — an offer. None of
   * them knows about Booking for, and none should have to: the selection is
   * search state, it is already in the query string, and this host is mounted
   * on the route that owns it. It is then written explicitly into the request
   * URL, because that URL is built from scratch and would otherwise lose it.
   */
  const searchParams = useSearchParams();
  const travelerId = parseBookingFor(searchParams);

  /**
   * Guards against a second press while the first is still minting a review.
   *
   * Pressing twice would create two held offers and two clientRefs, and the
   * second navigation would land on a different one than the toast was about.
   * A ref rather than state: nothing renders from it, and a re-render between
   * the two presses is exactly what we are not relying on.
   */
  const starting = useRef(false);

  useEffect(() => {
    const unsubscribe = subscribeToApprovalRequests((event: ApprovalRequestEvent) => {
      if (starting.current) return;

      // `createFlightReview` types these as objects; the bus carries them as
      // `unknown[]` because the four ported surfaces hand over whatever Amadeus
      // sent without inspecting it. Narrowed here, at the one boundary that
      // cares, rather than loosening the client's signature.
      const offers = (event.selectedOffers ?? []).filter(
        (offer): offer is Record<string, unknown> => !!offer && typeof offer === "object"
      );
      if (offers.length === 0) {
        // The bus carried no raw offers — a wiring fault rather than anything
        // the employee did, so say something useful instead of navigating to a
        // page that cannot load.
        logger.error("[RequestApprovalHost] approval event carried no offers");
        toast.error("Unable to start the request. Please refresh and try again.", {
          id: "flight-approval-request",
        });
        return;
      }

      starting.current = true;
      toast.loading("Preparing your request…", { id: "flight-approval-request" });

      void (async () => {
        try {
          // clientRef omitted — search-service mints it and returns it, rather
          // than the browser inventing one the later calls cannot resolve.
          const result = await createFlightReview({ selectedOffers: offers });
          if (!result.success || !result.data?.clientRef) {
            // Deliberately NOT `result.message`. createFlightReview is a
            // byte-identical port and its failure message is a raw transport
            // string — an offline browser produces the literal "Failed to
            // fetch", which was reaching employees as a toast. Nothing it
            // returns here is written for a person, so the copy is ours and
            // the real text goes to the log.
            logger.error("[RequestApprovalHost] could not mint a flight review", {
              detail: result.message,
            });
            toast.error("Unable to start the request. Please try again.", {
              id: "flight-approval-request",
            });
            return;
          }
          // Carry the search they are leaving, so Back from step 1 returns to
          // these exact results — and with them, the Booking for selection.
          const backHref = `${window.location.pathname}${window.location.search}`;
          toast.dismiss("flight-approval-request");
          router.push(getFlightReviewPageHref(result.data.clientRef, backHref, travelerId));
        } catch (error) {
          logger.error("[RequestApprovalHost] could not start the request", { error });
          toast.error("Unable to start the request. Please try again.", {
            id: "flight-approval-request",
          });
        } finally {
          // Released on failure so a retry works, and on success too — the
          // route change unmounts this host anyway.
          starting.current = false;
        }
      })();
    });
    return unsubscribe;
  }, [router, travelerId]);

  // Renders nothing: the flow it starts is a route, not an overlay.
  return null;
}
