"use client";

import { useSearchParams } from "next/navigation";
import { UserRound, X } from "lucide-react";

import {
  BOOKING_FOR_PARAM,
  airportsFromSegments,
  parseBookingFor,
} from "@/services/employee-requests/booking-for";
import { parseItinerary } from "@/services/flights/searchUrl";
import { useBookableTravellers } from "./useBookableTravellers";

/**
 * "You are booking for Esha Sharma" — shown above the results whenever the
 * trip is being requested for somebody else.
 *
 * ── Why this exists at all ────────────────────────────────────────────────
 *
 * The one error this feature can produce that nobody notices until a ticket is
 * issued is **filing a trip under the wrong person's name**. The selection
 * lives in a 168px cell on a bar that scrolls away, survives in the URL across
 * a whole session of searching, and changes nothing about the results — so
 * there is no other signal at all that the next "Request approval" will not be
 * for you.
 *
 * It renders nothing on a self-request, which is the overwhelmingly common
 * case: a banner that is always there is a banner nobody reads.
 *
 * Not a toast. The condition persists for as long as the selection does, and
 * something that dismisses itself after four seconds cannot state a condition.
 */
export function BookingForBanner() {
  const searchParams = useSearchParams();
  const bookingFor = parseBookingFor(searchParams);
  const airports = airportsFromSegments(parseItinerary(searchParams.get("itinerary")));

  // Same query key the field uses, so this is the cache entry it already
  // populated rather than a second request for the same list.
  const { travellers, isLoading } = useBookableTravellers({
    airports,
    enabled: bookingFor !== null,
  });

  if (bookingFor === null) return null;

  const traveller = travellers.find((t) => t.businessUserId === bookingFor) ?? null;

  // While the list loads there is nothing truthful to say — naming the wrong
  // person for a moment is worse than saying nothing for a moment.
  if (!traveller && isLoading) return null;

  const clearHref = (() => {
    const next = new URLSearchParams(searchParams.toString());
    next.delete(BOOKING_FOR_PARAM);
    const qs = next.toString();
    return qs ? `?${qs}` : "?";
  })();

  return (
    <div className="webNewContent container">
      <div
        role="status"
        className="mt-[12px] flex flex-wrap items-center gap-x-[10px] gap-y-[6px] rounded-[10px] border border-[#f6d38b] bg-[#fff8e8] px-[14px] py-[10px]"
      >
        <UserRound aria-hidden className="size-[16px] shrink-0 text-[#b45309]" />
        <p className="m-0 text-[13px] leading-[18px] text-[#7a4a06]">
          {traveller ? (
            <>
              You are booking for{" "}
              <strong className="font-semibold text-[#5c3704]">{traveller.name}</strong>
              <span className="text-[#8a6224]"> · {traveller.workEmail}</span>. Their travel policy
              applies, and you stay the requester.
            </>
          ) : (
            <>
              The colleague this search was for can no longer be selected. Switch back to yourself
              before requesting approval.
            </>
          )}
        </p>
        {/* A plain link, not a button: it only edits the URL, so it works
            before hydration and can be opened in a new tab like any other. */}
        <a
          href={clearHref}
          className="ml-auto inline-flex min-h-[32px] items-center gap-[4px] rounded-[8px] px-[8px] text-[13px] font-semibold text-[#7a4a06] underline-offset-2 hover:underline"
        >
          <X aria-hidden className="size-[14px]" />
          Book for myself
        </a>
      </div>
    </div>
  );
}
