"use client";

import { travellerRowsFor, type ScopeDraft } from "@/services/travel-policy/policy-format";
import type { TravelPolicyLimits } from "@/services/employee-requests/fare-policy";
import type { HotelPolicyLimits } from "@/services/employee-requests/hotel-policy";
import type { HomeSearchTab } from "../HomeSearchPanel";
import { HomeCard, HomeSection, HomeSkeleton } from "./HomeSection";

/**
 * "Your travel policy" — E0 (LEIS-1017).
 *
 * ── Why the rows come from the admin's own definitions ──────────────────
 *
 * The ticket is explicit: "same wording as the admin's Preview traveler
 * summary". `TRAVELLER_ROWS` / `HOTEL_TRAVELLER_ROWS` in policy-format.ts ARE
 * that preview, and they already answer the "blank limits show No limit"
 * requirement — `'No limit'`, `'No minimum'`, `'Any'` are written there. So
 * this adapts the employee-facing API response into the shape those renderers
 * expect rather than restating a dozen sentences that would then drift from
 * what the admin is shown while editing them.
 *
 * ── The one row that is dropped ─────────────────────────────────────────
 *
 * "Book for colleagues". `GET /policy/me` does not return it — the colleague
 * gate lives on `GET /business/travellers`, because it is a rule about the
 * dropdown rather than about the trip. Rendering it from a value this endpoint
 * does not carry would mean guessing, and a wrong "Not allowed" is worse than
 * an absent row on a panel whose whole job is to be trusted.
 */

/**
 * `isOn: false` means the rule is NOT CHECKED, which is a blank limit — never
 * a limit of zero, which would flag every trip. Mirrors `toDraftValue`'s rule
 * for the admin side; see its comment.
 */
function limit(rule: { isOn: boolean; value: unknown } | undefined): string {
  if (!rule?.isOn) return "";
  const value = rule.value;
  return typeof value === "number" || typeof value === "string" ? String(value) : "";
}

function flightDraft(limits: TravelPolicyLimits, scope: "DOMESTIC_FLIGHT" | "INTERNATIONAL_FLIGHT"): ScopeDraft {
  const gate = limits.gates?.[scope];
  return {
    approvalMode: gate?.approvalRequired ? "APPROVAL_REQUIRED" : "NO_APPROVAL_REQUIRED",
    minDaysBeforeDeparture: limit(limits.rules?.minDaysBeforeDeparture),
    maxFarePerTrip: limit(limits.rules?.maxFarePerTrip),
    allowedCabins: limits.rules?.allowedCabins?.isOn
      ? ((limits.rules.allowedCabins.value as string[] | null) ?? [])
      : [],
    allowExtraBaggage: Boolean(gate?.extraBaggageAllowed),
  };
}

function hotelDraft(limits: HotelPolicyLimits, scope: "DOMESTIC_HOTEL" | "INTERNATIONAL_HOTEL"): ScopeDraft {
  const gate = limits.gates?.[scope];
  return {
    approvalMode: gate?.approvalRequired ? "APPROVAL_REQUIRED" : "NO_APPROVAL_REQUIRED",
    minDaysBeforeCheckIn: limit(limits.rules?.minDaysBeforeCheckIn),
    maxStarRating: limit(limits.rules?.maxStarRating),
    maxNightlyRate: limit(limits.rules?.maxNightlyRate),
    maxLengthOfStay: limit(limits.rules?.maxLengthOfStay),
    restrictedBookingFlags: limits.rules?.restrictedBookingFlags?.isOn
      ? ((limits.rules.restrictedBookingFlags.value as string[] | null) ?? [])
      : [],
  };
}

export function TravelPolicyPanel({
  tab,
  flight,
  hotel,
  groupName,
  /** Named when the policy shown is a colleague's rather than the reader's. */
  travellerName,
}: {
  tab: HomeSearchTab;
  flight: TravelPolicyLimits | null;
  hotel: HotelPolicyLimits | null;
  groupName: string | null;
  travellerName?: string | null;
}) {
  const isHotels = tab === "hotels";
  const limits = isHotels ? hotel : flight;
  const scope = isHotels ? "DOMESTIC_HOTEL" : "DOMESTIC_FLIGHT";

  const rows = travellerRowsFor(scope).filter((row) => !row.settings.includes("colleagueBooking"));
  const draft = isHotels
    ? hotel && hotelDraft(hotel, "DOMESTIC_HOTEL")
    : flight && flightDraft(flight, "DOMESTIC_FLIGHT");

  return (
    <HomeSection title="Your travel policy">
      <HomeCard>
        <p className="m-0 mb-[14px] text-[13px]" style={{ color: "var(--fra-muted)" }}>
          {travellerName ? `${travellerName} · ` : ""}
          {groupName ?? "Your group"} · {isHotels ? "Domestic hotels" : "Domestic flights"}
        </p>

        <div aria-live="polite" aria-busy={!limits}>
          {!limits || !draft ? (
            <>
              <span className="sr-only">Loading your travel policy…</span>
              <HomeSkeleton rows={4} height={28} />
            </>
          ) : (
            <dl className="m-0 grid gap-[10px]">
              {rows.map((row) => (
                <div key={row.label} className="flex items-baseline justify-between gap-[16px]">
                  <dt className="text-[14px]" style={{ color: "var(--fra-muted)" }}>
                    {row.label}
                  </dt>
                  <dd
                    className="m-0 text-right text-[14px] font-semibold"
                    style={{ color: "var(--fra-heading)" }}
                  >
                    {row.render(draft)}
                  </dd>
                </div>
              ))}
            </dl>
          )}
        </div>

        <p
          className="mt-[14px] mb-0 border-t pt-[12px] text-[13px]"
          style={{ color: "var(--fra-muted)", borderColor: "var(--fra-border)" }}
        >
          Options outside these rules still show in search with a flag. You can request them
          with a business justification.
        </p>
      </HomeCard>
    </HomeSection>
  );
}
