'use client';

import { useState, useEffect, useRef } from "react";
import {
  CONTINUE_LABEL,
  REQUEST_APPROVAL_PENDING_LABEL,
  requestFlightApproval,
} from "@/services/flights/approvalRequest";
import FlightFareCard from './FlightFareCard';
// corp: the travel-policy badges LEIS-962 adds to this overlay.
import {
  CabinFlagMark,
  FarePolicyBadge,
  useTravelPolicyLimits,
} from "./FarePolicyBadge";
import { cabinFlagged, evaluateFare } from "@/services/employee-requests/fare-policy";
import Modal from "@/components/ui/Modal";
import type {
  CabinClass,
  FareOption,
  FareRules,
  FlightData,
} from "./types";
import { toast, TOAST_IDS } from "@/lib/toast";
import { collectSelectedOffers } from "@/services/flights/selection.client";
import type { FlightTripType } from "@/utils/tracking";

/**
 * Which raw offer actually books the fare the traveller picked. A Branded
 * Fares Upsell tier prices and books as its own distinct Amadeus offer
 * (FareOption._rawOffer) — different from the flight card's own
 * FlightData._rawOffer, which is always the base/default tier's. Falls back
 * to the flight's own offer only when the tier has none (the
 * single-fare-option case in buildFareOptionsList, where they're the same
 * offer anyway) or when nothing was actually selected.
 */
function resolveSelectedRawOffer(
  flight: FlightData,
  fareId: string | undefined
): Record<string, unknown> | undefined {
  const fare = fareId ? flight.fareOptions?.find((f) => f.id === fareId) : undefined;
  return fare?._rawOffer ?? flight._rawOffer;
}

const CABIN_LABELS: Record<CabinClass, string> = {
  economy: "Economy",
  "premium-economy": "Premium Economy",
  business: "Business",
};

const CABIN_ORDER: CabinClass[] = ["economy", "premium-economy", "business"];

interface FlightFaresModalProps {
  isOpen: boolean;
  onClose: () => void;
  /** Single-flight mode */
  flight?: FlightData;
  onSelectFare?: (fareId: string) => void;
  /** Multi-flight mode (round-trip): provide 2+ flights */
  flights?: FlightData[];
  /** Tab labels for multi-flight mode, e.g. ["Depart: NYC - LHR", "Return: LHR - NYC"] */
  flightLabels?: string[];
  onSelectFares?: (fareIds: Record<string, string>) => void;
  /**
   * Which kind of trip the selection is, for campaign reporting. Passed in because it
   * cannot be read off the offers: round-trip and multi-city both hand this modal a
   * `flights` array of single-leg offers that look identical.
   */
  tripType?: FlightTripType;
}

/** Shared single-flight fare picker UI */
function FlightFarePicker({
  flight,
  selectedFareId,
  onSelectFareId,
  onOpenRules,
  disabled = false,
}: {
  flight: FlightData;
  selectedFareId: string;
  onSelectFareId: (id: string) => void;
  onOpenRules: (name: string, rules: FareRules) => void;
  disabled?: boolean;
}) {
  const fareOptions = flight.fareOptions ?? [];

  const grouped = fareOptions.reduce(
    (acc, fare) => {
      const key: CabinClass = fare.cabinClass ?? "economy";
      const list = acc[key] ?? [];
      list.push(fare);
      acc[key] = list;
      return acc;
    },
    {} as Partial<Record<CabinClass, FareOption[]>>,
  );

  const availableTabs = CABIN_ORDER.filter(
    (k) => (grouped[k]?.length ?? 0) > 0,
  );
  const [activeTab, setActiveTab] = useState<CabinClass>(
    availableTabs[0] ?? "economy",
  );

  const currency = fareOptions[0]?.currency ?? "$";
  const leg = flight.outbound;

  /*
   * corp (LEIS-962): the traveller's group limits, fetched once for the whole
   * grid rather than previewed per cell. Null while loading, and null for good
   * when there is no business session or the call failed — the badges then
   * simply do not render. Step 4 gives the authoritative verdict either way.
   */
  const policyLimits = useTravelPolicyLimits();
  // `dateTime`, not `date` — the leg carries an ISO timestamp; evaluateFare
  // takes the calendar date off the front of it.
  const departDate = leg?.departure?.dateTime ?? null;
  const routeStr = `${leg.departure.city} (${leg.departure.airport}) → ${leg.arrival.city} (${leg.arrival.airport})`;
  const timeStr = `Departure at ${leg.departure.time} - Arrival at ${leg.arrival.time}`;

  function startingPrice(fares: FareOption[]): number {
    return Math.min(...fares.map((f) => f.pricePerPerson));
  }

  return (
    <div className="d-flex flex-column gap-3">
      {/* Flight info row */}
      <div className="d-flex align-items-start gap-2">
        <div className="d-flex flex-wrap gap-2">
          <div className="subHeading text-capitalize text-sm color-text-dark fw-bolder mb-0">
            {leg.airline.name}
          </div>
          <h4 className="text-sm fw-500 color-text-dark mb-0">{routeStr}</h4>
          <span className="text-sm">{timeStr}</span>
        </div>
      </div>

      {/* Cabin class tabs */}
      <ul
        className="nav nav-tabs custom-tabs fare-class-tab overflow-x-auto overflow-y-hidden flex-nowrap"
        role="tablist"
      >
        {availableTabs.map((key) => (
          <li key={key} className="nav-item" role="presentation">
            <button
              type="button"
              role="tab"
              aria-selected={activeTab === key}
              disabled={disabled}
              className={`nav-link border-end d-flex flex-column text-start opacity-100 color-text-dark text-lg fw-600 text-nowrap${activeTab === key ? " active" : ""}`}
              onClick={() => setActiveTab(key)}
            >
              <span className="text-sm color-text-dark fw-600">
                {CABIN_LABELS[key]}
                {/* corp: flagged, never disabled — LEIS-962 is explicit that a
                    cabin the group does not allow stays selectable. */}
                {cabinFlagged(key, policyLimits) ? <CabinFlagMark /> : null}
              </span>
              <span className="text-sm">
                Starting at {currency}
                {startingPrice(grouped[key]!)}
              </span>
            </button>
          </li>
        ))}
      </ul>

      {/* Fare cards per cabin tab */}
      <div className="tab-content">
        {availableTabs.map((key) => (
          <div
            key={key}
            className={`tab-pane fade${activeTab === key ? " show active" : ""}`}
            role="tabpanel"
          >
            <div className="d-flex table-responsive gap-3 py-3">
              {(grouped[key] ?? []).map((fare) => (
                <div key={fare.id} className="flex-price-col">
                  <FlightFareCard
                    fare={fare}
                    groupName={`fareSelection-${flight.id}`}
                    selected={selectedFareId === fare.id}
                    disabled={disabled}
                    onSelect={onSelectFareId}
                    onOpenRules={onOpenRules}
                    // corp (LEIS-962). Undefined when there is no policy to
                    // judge against, so the card renders exactly as upstream.
                    policyBadge={
                      policyLimits ? (
                        <FarePolicyBadge
                          verdict={evaluateFare({ fare, limits: policyLimits, departDate })}
                        />
                      ) : undefined
                    }
                  />
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default function FlightFaresModal({
  isOpen,
  onClose,
  flight,
  onSelectFare,
  flights,
  flightLabels,
  onSelectFares,
  tripType,
}: FlightFaresModalProps) {
  const isMulti = (flights?.length ?? 0) > 1;
  // corp: no router here any more — requesting approval does not navigate.
  const [isContinuing, setIsContinuing] = useState(false);
  /*
   * corp (LEIS-962). Read HERE as well as in FlightFarePicker because this
   * modal renders its cabin tabs and fare cards TWICE — the picker for a
   * multi-leg selection, and the block below for a single flight. That
   * duplication already bit once, when only one of the modal's two Continue
   * buttons was relabelled; badging only the picker meant a one-way search,
   * which is most of them, showed no badges at all.
   */
  const singlePolicyLimits = useTravelPolicyLimits();
  const continueLockRef = useRef(false);
  // ── Single-flight state ──
  const singleFareOptions = flight?.fareOptions ?? [];
  const singleGrouped = singleFareOptions.reduce(
    (acc, fare) => {
      const key: CabinClass = fare.cabinClass ?? "economy";
      const list = acc[key] ?? [];
      list.push(fare);
      acc[key] = list;
      return acc;
    },
    {} as Partial<Record<CabinClass, FareOption[]>>,
  );
  const singleAvailableTabs = CABIN_ORDER.filter(
    (k) => (singleGrouped[k]?.length ?? 0) > 0,
  );
  const singleDefaultTab = singleAvailableTabs[0] ?? "economy";

  const [activeTab, setActiveTab] = useState<CabinClass>(singleDefaultTab);
  const [selectedFareId, setSelectedFareId] = useState<string>("");

  /**
   * The fare the sticky footer prices — whatever the radios currently point at.
   *
   * Declared after the state it reads, not above it: `const` is hoisted but
   * not initialised, so reading it earlier in the body throws
   * "Cannot access 'selectedFareId' before initialization" on the first render.
   */
  const selectedFare = singleFareOptions.find((f) => f.id === selectedFareId);

  // ── Multi-flight state ──
  const [activeFlightTab, setActiveFlightTab] = useState(0);
  const [selectedFareIds, setSelectedFareIds] = useState<
    Record<string, string>
  >({});

  // ── Shared state ──
  const [openRules, setOpenRules] = useState<{
    name: string;
    rules: FareRules;
  } | null>(null);
  // Set when Continue is pressed with a leg still unpicked. Rendered next to
  // Continue (and, in multi mode, on the leg's own tab) so the message sits
  // where the missing choice is, not only in a toast that scrolls away.
  const [fareError, setFareError] = useState<string>("");

  // Reset when modal opens
  useEffect(() => {
    if (isOpen) {
      // The recommended fare comes in pre-selected — search-service already
      // picked it out as the one worth defaulting to, so making the traveller
      // click it again (when every other tier still needs an explicit click)
      // is just friction with no upside.
      const recommendedSingle = singleFareOptions.find((f) => f.recommended);
      setActiveTab(recommendedSingle?.cabinClass ?? singleDefaultTab);
      setSelectedFareId(recommendedSingle?.id ?? "");
      setActiveFlightTab(0);
      setSelectedFareIds(
        (flights ?? []).reduce(
          (acc, f) => {
            const opts = f.fareOptions ?? [];
            // Pre-select the only fare when a flight carries just one option
            // (e.g. multicity, where each leg has a single price rather than
            // several cabin tiers to compare) — nothing to choose between, so
            // don't make Continue wait on re-clicking a radio that's the only
            // choice anyway. Otherwise default to this leg's recommended fare,
            // same as the single-flight case above.
            if (opts.length === 1) {
              acc[f.id] = opts[0].id;
            } else {
              const recommended = opts.find((o) => o.recommended);
              if (recommended) acc[f.id] = recommended.id;
            }
            return acc;
          },
          {} as Record<string, string>,
        ),
      );
      setOpenRules(null);
      setFareError("");
      setIsContinuing(false);
      continueLockRef.current = false;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen]);

  const currency = singleFareOptions[0]?.currency ?? "$";

  const leg = flight?.outbound;
  const routeStr = leg
    ? `${leg.departure.city} (${leg.departure.airport}) → ${leg.arrival.city} (${leg.arrival.airport})`
    : "";
  const timeStr = leg
    ? `Departure at ${leg.departure.time} - Arrival at ${leg.arrival.time}`
    : "";

  function startingPrice(fares: FareOption[]): number {
    return Math.min(...fares.map((f) => f.pricePerPerson));
  }

  function unlockContinue() {
    continueLockRef.current = false;
    setIsContinuing(false);
  }

  function handleModalClose() {
    if (isContinuing || continueLockRef.current) return;
    onClose();
  }

  async function handleContinue() {
    if (isContinuing || continueLockRef.current) return;

    if (isMulti) {
      const legs = flights ?? [];
      // Continue only shows on the last tab, so an earlier leg can still be
      // unpicked when it's clicked — jump back to the first one that is.
      const missingIndex = legs.findIndex((f) => !selectedFareIds[f.id]);
      if (missingIndex !== -1) {
        const label = flightLabels?.[missingIndex];
        const message = label
          ? `Please select a fare for ${label} to continue.`
          : "Please select a fare for each flight to continue.";
        setActiveFlightTab(missingIndex);
        setFareError(message);
        toast.error(message, { id: TOAST_IDS.flightFareSelection });
        return;
      }
      onSelectFares?.(selectedFareIds);
    } else {
      if (!selectedFareId) {
        const message = "Please select a fare to continue.";
        setFareError(message);
        toast.error(message, { id: TOAST_IDS.flightFareSelection });
        return;
      }
      onSelectFare?.(selectedFareId);
    }

    setFareError("");

    // Generic 1..N offer list: one-way/round-trip = the card opened via View Fares;
    // multi-city = every selected leg passed into this modal. Each entry's
    // _rawOffer is resolved to the SELECTED fare tier's own offer — reported
    // bug: this used to pass the flight cards through unchanged, so
    // collectSelectedOffers always read FlightData._rawOffer (the base
    // tier), silently ignoring whichever tier the radio buttons actually had
    // selected.
    const selectedFlights = isMulti
      ? (flights ?? []).map((f) => ({ _rawOffer: resolveSelectedRawOffer(f, selectedFareIds[f.id]) }))
      : flight
        ? [{ _rawOffer: resolveSelectedRawOffer(flight, selectedFareId) }]
        : [];
    const selectedOffers = collectSelectedOffers(selectedFlights);

    if (selectedOffers.length === 0) {
      toast.error("Unable to continue. Please select a flight again.");
      return;
    }

    continueLockRef.current = true;
    setIsContinuing(true);
    setOpenRules(null);

    /*
     * corp: this is where leisure-ui created a booking review and pushed the
     * traveller to the review page. corp has no booking funnel — the employee
     * requests approval and an admin decides — so the selection stops here.
     *
     * `selectedOffers` above already resolved each flight to the fare tier the
     * radio buttons actually selected, which is exactly what the request will
     * need, so it is passed through rather than recollected.
     */
    try {
      await requestFlightApproval({
        flights: isMulti ? (flights ?? []) : flight ? [flight] : [],
        tripType,
        selectedOffers,
      });
    } finally {
      // Nothing navigates away, so the modal has to hand control back itself.
      unlockContinue();
    }
  }

  return (
    <>
      <Modal
        isOpen={isOpen}
        onClose={handleModalClose}
        size="xl"
        showCloseButton={!isContinuing}
        closeOnBackdrop={!isContinuing}
        className="modalZoom modal-class"
        title="Flight Details and Fare Options available for you!"
        titleClassName="subHeading fw-600 pe-5 mb-0"
      >
        {isMulti && flights ? (
          /* ── Multi-flight (round-trip) mode ── */
          <div
            className="d-flex flex-column gap-3 bgColor-white booking-form-section px-3"
            id="view-fareModal"
            aria-busy={isContinuing}
          >
            {/* Outer flight tabs */}
            <ul
              className="nav nav-tabs flight-nav-tabs custom-tabs overflow-x-auto overflow-y-hidden flex-nowrap"
              data-tab-group="bookingTabs"
            >
              {flights.map((f, i) => {
                const label =
                  flightLabels?.[i] ??
                  `Flight ${i + 1}: ${f.outbound.departure.airport} - ${f.outbound.arrival.airport}`;
                return (
                  <li key={f.id} className="nav-item">
                    <button
                      type="button"
                      className={`nav-link opacity-100 text-lg fw-600 text-nowrap${activeFlightTab === i ? " active" : " color-text-dark"}`}
                      disabled={isContinuing}
                      onClick={() => setActiveFlightTab(i)}
                    >
                      {label}
                    </button>
                  </li>
                );
              })}
            </ul>
            {/* Tab panes */}
            <div
              className="tab-content flight-tab-content gap-3"
              data-tab-group="bookingTabs"
            >
              {flights.map((f, i) => {
                const isLast = i === flights.length - 1;
                return (
                  <div
                    key={f.id}
                    className={`tab-pane from-to-tab-pane fade${activeFlightTab === i ? " show active" : ""}`}
                    id={`booking-tab-${i}`}
                  >
                    <FlightFarePicker
                      flight={f}
                      selectedFareId={selectedFareIds[f.id] ?? ""}
                      disabled={isContinuing}
                      onSelectFareId={(fareId) => {
                        setFareError("");
                        setSelectedFareIds((prev) => ({
                          ...prev,
                          [f.id]: fareId,
                        }));
                      }}
                      onOpenRules={(name, rules) =>
                        setOpenRules({ name, rules })
                      }
                    />
                    {/* Footer nav */}
                    <div
                      className={`d-flex justify-content-end align-items-center gap-2 pt-3 border-top${isLast ? "" : ""}`}
                    >
                      {fareError && !selectedFareIds[f.id] && (
                        <span
                          role="alert"
                          className="text-sm color-text-second me-auto text-start"
                        >
                          {fareError}
                        </span>
                      )}
                      {i > 0 && (
                        <button
                          type="button"
                          className="tab-back-btn buttons btnColor-first-outline rounded-3 h-auto px-3 py-2 text-lg fw-600 ls-0"
                          disabled={isContinuing}
                          onClick={() => setActiveFlightTab(i - 1)}
                        >
                          Back
                        </button>
                      )}
                      {isLast ? (
                        <button
                          type="button"
                          className="tab-next-btn d-inline-flex buttons btnColor-second rounded-3 px-3 py-2 text-lg fw-500"
                          onClick={handleContinue}
                          disabled={isContinuing}
                        >
                          {isContinuing ? REQUEST_APPROVAL_PENDING_LABEL : CONTINUE_LABEL}
                        </button>
                      ) : (
                        <button
                          type="button"
                          className="tab-next-btn d-inline-flex buttons btnColor-second rounded-3 px-3 py-2 text-lg fw-500"
                          onClick={() => setActiveFlightTab(i + 1)}
                          disabled={isContinuing}
                        >
                          Next
                        </button>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        ) : (
          /* ── Single-flight mode (original) ── */
          <div
            className="d-flex flex-column gap-3 bgColor-white booking-form-section px-3"
            aria-busy={isContinuing}
          >
            {/* Flight info row */}
            <div className="d-flex align-items-start gap-2">
              <div className="d-flex flex-wrap gap-2 align-items-center">
                <div className="subHeading text-capitalize text-sm color-text-dark fw-bolder mb-0">
                  {leg?.airline.name}
                </div>
                <h4 className="text-sm fw-500 color-text-dark mb-0">
                  {routeStr}
                </h4>
                <span className="text-sm text-muted">{timeStr}</span>
              </div>
            </div>

            {/* Cabin class tabs */}
            <ul
              className="nav nav-tabs custom-tabs fare-class-tab overflow-x-auto overflow-y-hidden flex-nowrap"
              role="tablist"
            >
              {singleAvailableTabs.map((key) => (
                <li key={key} className="nav-item" role="presentation">
                  <button
                    type="button"
                    role="tab"
                    aria-selected={activeTab === key}
                    className={`nav-link border-end d-flex flex-column text-start opacity-100 color-text-dark text-lg fw-600 text-nowrap${activeTab === key ? " active" : ""}`}
                    onClick={() => setActiveTab(key)}
                    disabled={isContinuing}
                  >
                    <span className="text-sm color-text-dark fw-600">
                      {CABIN_LABELS[key]}
                      {/* corp: flagged, never disabled (LEIS-962). */}
                      {cabinFlagged(key, singlePolicyLimits) ? <CabinFlagMark /> : null}
                    </span>
                    <span className="text-sm">
                      Starting at {currency}
                      {startingPrice(singleGrouped[key]!)}
                    </span>
                  </button>
                </li>
              ))}
            </ul>

            {/* Fare cards per tab */}
            <div className="tab-content">
              {singleAvailableTabs.map((key) => (
                <div
                  key={key}
                  className={`tab-pane fade${activeTab === key ? " show active" : ""}`}
                >
                  <div className="d-flex table-responsive gap-3 pt-3">
                    {(singleGrouped[key] ?? []).map((fare) => (
                      <div key={fare.id} className="flex-price-col">
                        <FlightFareCard
                          fare={fare}
                          groupName={`fareSelection-single-${flight?.id ?? 'flight'}`}
                          selected={selectedFareId === fare.id}
                          disabled={isContinuing}
                          onSelect={(id) => {
                            setFareError("");
                            setSelectedFareId(id);
                          }}
                          onOpenRules={(name, rules) => setOpenRules({ name, rules })}
                          policyBadge={
                            singlePolicyLimits ? (
                              <FarePolicyBadge
                                verdict={evaluateFare({
                                  fare,
                                  limits: singlePolicyLimits,
                                  departDate: flight?.outbound?.departure?.dateTime ?? null,
                                })}
                              />
                            ) : undefined
                          }
                        />
                      </div>
                    ))}
                  </div>
                </div>
              ))}
            </div>

            {/* Request approval */}
            {/* Pinned to the bottom of the modal on a phone, with the fare
                being bought beside it — stacked cards push Continue off the
                screen, and a button you have to scroll to find is one people
                assume is not there. */}
            <div className="d-flex justify-content-end align-items-center pt-3 border-top flight-fare-actions">
              <span className="flight-fare-actions__total">
                <span className="flight-fare-actions__amount">
                  {selectedFare?.currency}
                  {selectedFare?.pricePerPerson}
                </span>
                <span className="flight-fare-actions__unit">per adult</span>
              </span>
              {fareError && (
                <span
                  role="alert"
                  className="text-sm color-text-second me-auto text-start"
                >
                  {fareError}
                </span>
              )}
              <button
                type="button"
                className="d-inline-flex buttons btnColor-second rounded-3 px-3 py-2 text-lg fw-500"
                onClick={handleContinue}
                disabled={isContinuing}
              >
                {isContinuing ? REQUEST_APPROVAL_PENDING_LABEL : CONTINUE_LABEL}
              </button>
            </div>
          </div>
        )}
      </Modal>

      {/* Nested fare rules modal */}
      <Modal
        isOpen={!!openRules}
        onClose={() => {
          if (isContinuing) return;
          setOpenRules(null);
        }}
        title={openRules ? `Fare Rules — ${openRules.name}` : ""}
        titleClassName="subHeading fw-600 pe-5"
        size="md"
        closeOnBackdrop={!isContinuing}
        showCloseButton={!isContinuing}
        className="modalZoom modal-class"
      >
        <div className="bgColor-white booking-form-section px-3">
          {openRules?.rules.cancellation && (
            <>
              <h2 className="text-lg color-text-dark fw-semibold">
                Cancellation
              </h2>
              <p className="color-text-grey text-sm">
                {openRules.rules.cancellation}
              </p>
            </>
          )}
          {openRules?.rules.dateChange && (
            <>
              <h2 className="text-lg color-text-dark fw-semibold">
                Date Change
              </h2>
              <p className="color-text-grey text-sm">
                {openRules.rules.dateChange}
              </p>
            </>
          )}
          {openRules?.rules.baggage && (
            <>
              <h2 className="text-lg color-text-dark fw-semibold">Baggage</h2>
              <p className="color-text-grey text-sm">
                {openRules.rules.baggage}
              </p>
            </>
          )}
          {openRules?.rules.seatSelection && (
            <>
              <h2 className="text-lg color-text-dark fw-semibold">
                Seat Selection
              </h2>
              <p className="color-text-grey text-sm">
                {openRules.rules.seatSelection}
              </p>
            </>
          )}
          {openRules?.rules.nameChange && (
            <>
              <h2 className="text-lg color-text-dark fw-semibold">
                Name Change
              </h2>
              <p className="color-text-grey text-sm">
                {openRules.rules.nameChange}
              </p>
            </>
          )}
        </div>
      </Modal>
    </>
  );
}
