"use client";

import { Flag } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { useSearchParams } from "next/navigation";

import {
  evaluateFlightResult,
  getTravelPolicy,
  type FareVerdict,
  type TravelPolicyLimits,
} from "@/services/employee-requests/fare-policy";
import { parseBookingFor, airportsFromSegments } from "@/services/employee-requests/booking-for";
import { parseItinerary } from "@/services/flights/searchUrl";
import { useBusinessToken } from "@/components/employee-requests/use-session";
import { cn } from "cn";

/**
 * In policy / Out of policy, on a fare card or a cabin tab (LEIS-962).
 *
 * CORP-ONLY — leisure-ui has no travel policy. Kept in its own file rather than
 * inside FlightFaresModal so the ported modal's diff against upstream stays a
 * handful of lines rather than a hundred.
 *
 * The flags are rendered as text, not as a tooltip: PRD §7 says the flags
 * travel with the request to the approver, so the employee ought to be able to
 * read on the card what the approver will be reading later. A hover-only
 * explanation is also no explanation at all on a phone.
 */

/**
 * The limits for an explicitly given traveller and route.
 *
 * Takes its parameters rather than reading the URL, because the request flow
 * needs this too and `/flight-request` carries no `itinerary` param — the
 * route is in the priced offer there. Reading the URL in both places would
 * resolve that trip against an EMPTY airport list, which the server treats as
 * unclassifiable and falls to the stricter International tab: a domestic trip
 * would then be gated by the wrong tab's approval setting.
 *
 * The query key is shared with `useTravelPolicyLimits`, so arriving at the
 * request flow from the SRP for the same traveller and route is a cache hit
 * rather than a second request.
 */
export function useFlightPolicyLimits(params: {
  travelerId: string | null;
  airports: string[];
}): TravelPolicyLimits | null {
  const { travelerId, airports } = params;
  // No business session means nobody to judge: the SRP is reachable signed out.
  const token = useBusinessToken();

  const { data } = useQuery({
    // The traveller AND the route: the verdict is their group's, on the tab
    // this itinerary falls under.
    queryKey: ["travel-policy", travelerId ?? "self", airports.join(",")],
    queryFn: async () => {
      const res = await getTravelPolicy({ travelerId, airports });
      // A failure is not an error worth surfacing on a search page — the badges
      // simply do not render, and step 4 still gives the real verdict.
      return res.success ? (res.data ?? null) : null;
    },
    enabled: Boolean(token),
    staleTime: 5 * 60_000,
    retry: false,
  });

  return data ?? null;
}

/** The same, for pages that carry the traveller and itinerary in the URL. */
export function useTravelPolicyLimits(): TravelPolicyLimits | null {
  const searchParams = useSearchParams();
  return useFlightPolicyLimits({
    travelerId: parseBookingFor(searchParams),
    airports: airportsFromSegments(parseItinerary(searchParams.get("itinerary"))),
  });
}

export function FarePolicyBadge({
  verdict,
  className = "",
  showFlags = true,
  align = "start",
}: {
  verdict: FareVerdict;
  className?: string;
  /** Off where the caller lists the flags itself, so they are not said twice.
   *  On everywhere the badge is the only thing explaining the verdict. */
  showFlags?: boolean;
  /**
   * Which edge the badge and its flag text sit against.
   *
   * The flagged variant is a flex column, so its children would stretch to full
   * width and the pill would lose its shape — it has to pick an edge rather
   * than inherit one. `start` suits the fare list, where the badge sits under
   * left-aligned fare copy; `end` suits a search card's price column, which is
   * right-aligned throughout.
   */
  align?: "start" | "end";
}) {
  if (verdict.inPolicy) {
    return (
      <span
        className={`badge rounded-pill text-sm fw-500 ${className}`}
        style={{
          backgroundColor: "var(--fra-approved-bg, #e3f8ea)",
          color: "var(--fra-approved, #15803d)",
        }}
      >
        In policy
      </span>
    );
  }

  return (
    <span className={cn("d-inline-flex flex-column gap-1", `align-items-${align}`, `text-${align}`, className)}>
      <span
        className={cn("badge rounded-pill text-sm fw-500", `align-self-${align}`)}
        style={{
          backgroundColor: "var(--fra-pending-bg, #fff4dc)",
          color: "var(--fra-pending, #b45309)",
        }}
      >
        {verdict.flags.length} flag{verdict.flags.length === 1 ? "" : "s"}
      </span>
      {/* Spelled out, not hidden behind a tooltip — see the file comment. */}
      {showFlags && (
        <span className="text-xs" style={{ color: "var(--fra-muted, #6b7785)" }}>
          {verdict.flags.map((flag) => flag.label).join(" · ")}
        </span>
      )}
    </span>
  );
}

/**
 * The verdict on one search-result card (LEIS-981).
 *
 * Self-contained on purpose: `FlightCard` is a port of leisure-ui's, which has
 * no travel policy at all, so the whole dependency — the query, the evaluator,
 * the markup — lives here and the card spends two lines on it. Same reason
 * `FlightFaresModal` renders `FarePolicyBadge` rather than inlining it.
 *
 * Renders NOTHING when there is no policy to apply: signed out, still loading,
 * or the call failed. A green "In policy" nobody has earned is worse than no
 * badge, because a traveller would read it as a checked claim.
 *
 * The limits come from the URL — `bookingFor` and the itinerary — so a card
 * judges the trip the traveller actually searched, against the group of the
 * person they are booking for. Every card on the page shares one query key, so
 * this is one request for the whole list, not one per row.
 */
export function FlightResultPolicyBadge({
  flight,
}: {
  flight: Parameters<typeof evaluateFlightResult>[0]["flight"];
}) {
  const limits = useTravelPolicyLimits();
  if (!limits) return null;
  return (
    <FarePolicyBadge
      verdict={evaluateFlightResult({ flight, limits })}
      // `end`, because this sits in the card's PRICE column, which is
      // `align-items-end text-end` from "from" down to the Fares button. It
      // used to force `text-start`, which left the badge and its flag text as
      // the only things in that column hugging the opposite edge.
      align="end"
      className="mt-2"
    />
  );
}

/**
 * The flag a cabin tab carries when the group does not allow it.
 *
 * lucide, not a glyph or an emoji — corp's one icon set. The colour is stated
 * explicitly because this renders inside /srp, where Bootstrap's reboot sets a
 * body colour and anything relying on inheritance comes out #474646, icons
 * included (they stroke with `currentColor`).
 */
export function CabinFlagMark() {
  return (
    <Flag
      className="ms-1 d-inline-block align-middle"
      size={13}
      strokeWidth={2.5}
      style={{ color: "var(--fra-pending, #b45309)" }}
      aria-label="Out of policy cabin"
    >
      <title>Not an allowed cabin for this traveller</title>
    </Flag>
  );
}
