'use client';

import { memo, useState } from 'react';
import CompareToggle from './CompareToggle';
import { useCompareEntry } from './useCompareTray';
import type { FlightData } from './types';
import FlightRoute from './FlightRoute';
import FlightFaresModal from './FlightFaresModal';
import { FlightResultPolicyBadge } from './FarePolicyBadge';
import FlightItinerary, { FlightItineraryModal, FLIGHT_DETAILS_VIEW } from './FlightItinerary';
import { legSliceKey } from '@/services/flights/layoverScope';
import { FARES_LABEL } from '@/services/flights/approvalRequest';
import { describeFlightSelection, trackFlightEvent } from '@/services/flights/tracking';
import { trackMetaPixelEventOnce } from '@/lib/meta-pixel';

interface FlightCardProps {
  flight: FlightData;
  index: number;
  defaultExpandDetails?: boolean;
}

/**
 * Memoized — FlightsList virtualizes with measureElement (a ResizeObserver),
 * so expanding one card's details changes that row's height and triggers a
 * virtualizer re-render of every currently-mounted row (commonly 15-30+ with
 * overscan). Without memo, every sibling card re-ran its full render on that
 * single expand/collapse even though its own flight/index never changed —
 * that's the "laggy" expand.
 */
function FlightCard({ flight, index,  defaultExpandDetails = false }: FlightCardProps) {
  // corp: no router here any more — requesting approval does not navigate.
  const [showFaresModal, setShowFaresModal] = useState(false);
  const [showDetails, setShowDetails] = useState(defaultExpandDetails);
  const [selectedFareId, setSelectedFareId] = useState<string | undefined>(undefined);
  void selectedFareId; // used only for selection tracking
  // corp (LEIS-962): no `isGoingToReview` here any more. The card used to
  // short-circuit a single-fare offer into the request itself and needed a busy
  // state for it; every offer now opens the overlay, which owns its own
  // pending state on the Continue button.

  const detailSectionId = `flightDetailSection${index}`;
  const toggleDetails = () =>
    FLIGHT_DETAILS_VIEW === 'modal' ? setShowDetails(true) : setShowDetails((prev) => !prev);

  // One-way cards can still carry a bundled return leg, so the card itself is what knows
  // which it is — /srp/flights only ever lists single offers, but the same card renders
  // the combined itineraries on the round-trip page.
  const tripType = flight.inbound ? 'ROUNDTRIP' : 'ONEWAY';

  async function handleViewFares() {
    // The flight funnel's equivalent of a hotel card click: the traveller singled this
    // offer out. Fired whether it opens the fare picker or goes straight to review, since
    // which of those happens is a property of the offer (how many fares it has), not of
    // what the traveller did.
    void trackFlightEvent('SEE_AVAILABILITY_CLICK', describeFlightSelection([flight], tripType), {
      revenueAmount: flight.pricePerPerson,
      currency: flight.currency,
      metadata: { offerId: flight.id, fareOptions: flight.fareOptions?.length ?? 0, position: index },
    });

    // Meta's ViewContent — the flight equivalent of opening a hotel's detail page, which
    // is where hotels fire theirs. Keyed on the offer, so re-opening the same card's fares
    // is one view.
    trackMetaPixelEventOnce(`ViewContent:flight:${flight.id}`, 'ViewContent', {
      content_name: `${flight.outbound.departure.airport}-${flight.outbound.arrival.airport}`,
      content_category: 'Flight',
      content_ids: [flight.id],
      content_type: 'product',
      value: flight.pricePerPerson ?? 0,
      currency: flight.currency ?? 'USD',
    });

    // corp (LEIS-962): ALWAYS the overlay, even for a single fare.
    //
    // It used to skip straight to the request when there was only one fare,
    // on the reasoning that there was nothing to pick between. There is now:
    // the overlay carries the baggage, the inclusions and the policy verdict
    // for that fare, and LEIS-962 makes seeing them the point of the step —
    // "Fares opens the overlay for the chosen flight", with no exception for
    // a flight that happens to file one brand. Skipping it would hide the
    // In policy / Out of policy badge from exactly the fares nobody gets to
    // compare.
    setShowFaresModal(true);
  }

  const compare = useCompareEntry(flight);
  /** Names the flight for the control's assistive text — "Compare" alone would
   *  be identical on every card in the list. */
  const compareLabel = `${flight.outbound.airline.name} ${flight.outbound.departure.time} to ${flight.outbound.arrival.time}`;

  return (
    <div className="card rounded-start-3 w-100 bgColor-white p-3 m-0">
      <div className="row listing-row g-0 h-100">

        {/* Left: flight legs */}
        <div className="col-md-10">

          {/* Outbound leg — labeled "Onward" only when there's a return leg too */}
          {flight.inbound && (
            <span className="text-xs fw-600 flight-detail-label text-uppercase d-block mb-1">Onward</span>
          )}
          <div className="row">
            <FlightRoute
              leg={flight.outbound}
              sliceKey={legSliceKey(flight, 0)}
              showMobilePrice
              price={flight.pricePerPerson}
              currency={flight.currency}
            />
          </div>

          {/* Return leg — same card, same price, no separate selection or pricing.
              The divider is a border-top on this plain wrapper (not the .row above)
              since Bootstrap's .row has negative side margins for its gutters —
              a border applied directly to a .row bleeds past the card's edges. */}
          {flight.inbound && (
            <div className="pt-3 mt-3 border-top">
              <span className="text-xs fw-600 flight-detail-label text-uppercase d-block mb-1">Return</span>
              <div className="row">
                <FlightRoute leg={flight.inbound} sliceKey={legSliceKey(flight, 1)} isReturn />
              </div>
            </div>
          )}
        </div>

        {/* Right: price + actions */}
        <div className="col-md-2">
          <div className="col-12 border-start no-mobile-border pe-md-2 no-grid order-2 order-md-3 h-100">
            <div className="d-flex flex-column justify-content-center align-items-end text-end h-100">

              <div className="listing-div text-end d-flex justify-content-between align-items-end flex-column d-none d-sm-block">
                <small className="d-block mb-2 text-xs">from</small>
              </div>

              <div className="listing-div text-end d-flex justify-content-between align-items-end flex-column d-none d-sm-block">
                <h5 className="mb-0">
                  <span className="mainHeading flight-price-amount color-text-dark fw-bold">
                    {flight.currency}{flight.pricePerPerson}
                  </span>
                </h5>
                <small className="d-block color-text-dark text-xs mb-md-2">per adult</small>
              </div>

              {/* corp (LEIS-981): "Flight search results: badge In policy /
                  N flags per result". Renders nothing outside Business mode. */}
              <FlightResultPolicyBadge flight={flight} />

              <div className="d-flex d-md-block w-100 justify-content-between">
                <a className="order-1 order-md-4" role="button" onClick={toggleDetails}>
                  <small
                    /* corp: d-inline-flex, not d-block. `.listing-div` forces
                       text-align:left !important, so as a block the chevron
                       wrapped onto its own line under "Flight Details". Flexing
                       the row keeps the label and its chevron together and
                       centred, which is what the design shows. */
                    className="listing-div d-inline-flex align-items-center gap-1 fw-regular color-text-second mb-0 text-xs mt-md-2 mb-md-2 mt-3 flightnew-detail toggle-text-btn flight-card-link-btn cursor-pointer"
                    aria-expanded={FLIGHT_DETAILS_VIEW === 'inline' ? showDetails : undefined}
                    aria-controls={FLIGHT_DETAILS_VIEW === 'inline' ? detailSectionId : undefined}
                  >
                    <span className="toggle-btn-text color-text-second text-xs fw-400">
                      {FLIGHT_DETAILS_VIEW === 'inline' && showDetails ? 'Hide Details' : 'Flight Details'}
                    </span>
                    <svg
                      className="iconSize-12 stroke-second flight-card-chevron"
                      width="24"
                      height="24"
                      viewBox="0 0 24 24"
                      fill="none"
                      strokeWidth="2"
                    >
                      <path d="m6 9 6 6 6-6" />
                    </svg>
                  </small>
                </a>

                {flight.fareOptions && flight.fareOptions.length > 0 && (
                  <a
                    className="toggle-text-btn buttons btnColor-second text-center rounded-2 px-3 py-1 fw-normal position-relative me-0 w-auto text-sm mt-2 order-2 order-md-3 cursor-pointer"
                    role="button"
                    onClick={handleViewFares}
                  >
                    <span className="toggle-btn-text color-text-white-same text-sm fw-400">
                      {/* corp (LEIS-962): "Fares" for every offer. The label
                          used to be "Request approval" on a single-fare card
                          and "View Fares" otherwise — two labels for one
                          action, and the first promised a step this button no
                          longer takes you to. */}
                      {FARES_LABEL}
                    </span>
                  </a>
                )}
              </div>

            </div>
          </div>
        </div>
      </div>

      {/*
        Compare, on its own line under the card's content.
        Left-aligned and quiet: it is a secondary action beside View Fares, and
        a traveller comparing flights is still choosing, not yet booking.
      */}
      {compare.available && (
        <div className="flight-card-compare-row">
          <CompareToggle
            id={`compare-${index}`}
            isAdded={compare.isAdded}
            isFull={compare.isFull}
            onAdd={compare.add}
            onRemove={compare.remove}
            flightLabel={compareLabel}
          />
        </div>
      )}

      {/* Expandable panels — mounted only while open. FlightItinerary builds a
          nontrivial per-segment DOM tree; rendering it unconditionally (just
          hidden via the `collapse` class) meant every card in the virtualized
          window paid that cost on first paint whether or not it was ever
          opened. */}
      {FLIGHT_DETAILS_VIEW === 'inline' && showDetails && (
        <div className="flight-card-extra-info" id={`flightCardExtraInfo${index}`}>
          <div id={detailSectionId} className="collapse show">
            <FlightItinerary flight={flight} />
          </div>
        </div>
      )}

      {/* Flight details modal */}
      {FLIGHT_DETAILS_VIEW === 'modal' && (
        <FlightItineraryModal flight={flight} isOpen={showDetails} onClose={() => setShowDetails(false)} />
      )}

      {/* Fares modal */}
      {flight.fareOptions && flight.fareOptions.length > 0 && (
        <FlightFaresModal
          isOpen={showFaresModal}
          onClose={() => setShowFaresModal(false)}
          flight={flight}
          tripType={tripType}
          onSelectFare={setSelectedFareId}
        />
      )}
    </div>
  );
}

export default memo(FlightCard);
