"use client";

import { useSearchParams } from "next/navigation";

import {
  evaluateHotel,
  evaluateHotelResult,
  hasHotelPolicy,
  useHotelPolicyLimits,
  type HotelFacts,
  type HotelVerdict,
} from "@/services/employee-requests/hotel-policy";
import { parseBookingFor } from "@/services/employee-requests/booking-for";

/**
 * In policy / N flags, on a hotel search card or a room rate (LEIS-993 /
 * LEIS-1001).
 *
 * CORP-ONLY — leisure-ui has no travel policy. Kept in its own file for the
 * reason `FarePolicyBadge` is: `HotelCardV3` and `OfferDetailsBusiness` are
 * ports of leisure-ui components, and keeping the whole dependency — query,
 * evaluator, markup — here means those files spend two lines on policy instead
 * of a hundred.
 *
 * Flags are rendered as TEXT, not 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 read later; a hover-only explanation is also no
 * explanation at all on a phone.
 *
 * Nothing is ever hidden or disabled because of a flag. An out-of-policy
 * property stays in the list and an out-of-policy rate stays bookable — the
 * badge is the whole of the consequence.
 */

export function HotelPolicyBadge({
  verdict,
  className = "",
  showFlags = true,
}: {
  verdict: HotelVerdict;
  className?: string;
  /** Off where the caller lists the flags itself, so they are not said twice. */
  showFlags?: boolean;
}) {
  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={`d-inline-flex flex-column gap-1 ${className}`}>
      <span
        className="badge rounded-pill text-sm fw-500 align-self-start"
        style={{
          backgroundColor: "var(--fra-pending-bg, #fff4dc)",
          color: "var(--fra-pending, #b45309)",
        }}
      >
        {verdict.flags.length} flag{verdict.flags.length === 1 ? "" : "s"}
      </span>
      {showFlags && (
        <span className="text-xs" style={{ color: "var(--fra-muted, #6b7785)" }}>
          {verdict.flags.map((flag) => flag.label).join(" · ")}
        </span>
      )}
    </span>
  );
}

/**
 * The destination country for the tab, from the SRP's own query string.
 *
 * The search form carries the destination, not its country, so this reads the
 * country code the results themselves report. Until the first result lands it
 * is null, and the server then resolves to the International tab — the
 * stricter one, and the same convention the flight route uses for an
 * itinerary it cannot classify.
 */
function useSrpCountryCode(fallback: string | null): string | null {
  const searchParams = useSearchParams();
  return searchParams.get("countryCode") || fallback;
}

/**
 * The verdict on one hotel search-result card.
 *
 * 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.
 *
 * Every card on the page shares one query key, so this is one request for the
 * whole list rather than one per row.
 */
export function HotelCardPolicyBadge({
  hotel,
  checkIn,
  nights,
  className = "",
}: {
  hotel: {
    price?: number;
    taxes?: number;
    starRating?: number | null;
    address?: { country_code?: string };
    rawData?: { category?: string | null; chain_code?: string | null; property_code?: string };
  };
  checkIn?: string | null;
  nights?: number | null;
  className?: string;
}) {
  const searchParams = useSearchParams();
  const countryCode = useSrpCountryCode(hotel.address?.country_code ?? null);
  const limits = useHotelPolicyLimits({
    travelerId: parseBookingFor(searchParams),
    countryCode,
  });
  if (!hasHotelPolicy(limits)) return null;

  const verdict = evaluateHotelResult({ hotel, checkIn, nights, limits });
  return <HotelPolicyBadge verdict={verdict} className={className} />;
}

/**
 * The verdict on one room RATE, on the hotel details page.
 *
 * Unlike the search card this knows the rate, so it judges refundability too —
 * which is why a property badged "In policy" in the results can still contain a
 * flagged rate. The card was never a claim about every rate inside it.
 *
 * This reverses an earlier decision recorded in `OfferDetailsBusiness`: that
 * file used to say no rate carried a badge "by design, for now", because there
 * was no hotel policy to badge against. LEIS-993 is that policy.
 */
export function HotelRatePolicyBadge({
  facts,
  travelerId,
  countryCode,
  className = "",
}: {
  facts: HotelFacts;
  travelerId: string | null;
  countryCode: string | null;
  className?: string;
}) {
  const limits = useHotelPolicyLimits({ travelerId, countryCode });
  if (!hasHotelPolicy(limits)) return null;

  const verdict = evaluateHotel({ facts, limits });
  return <HotelPolicyBadge verdict={verdict} className={className} />;
}
