'use client';

import { useEffect, useRef, useState, useMemo } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { fetchFlightOffers, setActiveSort, resetFilters, setFilters, applyFlightFilters, sortFlights, searchIdentityKey } from '@/store/slices/flightSearch.slice';
import { applySmartPredicates } from '@/services/flights/smartFilters/applySmartPredicates';
import { describeActiveFilters, directOnlyOffers, type ActiveFilterChip } from '@/services/flights/filterSort';
import type { SortKey } from '@/store/slices/flightSearch.slice';
import type { FlightData } from './types';
import { parseItinerary, parseChildren, parseInfants, decodeCabinClass } from '@/services/flights/searchUrl';
import { parseFiltersFromParams } from '@/services/flights/filtersUrl';
import { useSyncSearchUrl } from './useSyncSearchUrl';
import { useCachedFlightSearch } from './useCachedFlightSearch';
import type { ResolvedLocation } from '@/services/flights/resolveFlightCityNames';
import FlightSortTabs from './FlightSortTabs';
import FlightsFilteredEmptyState from './FlightsFilteredEmptyState';
import FlightFilterSidebar from './FlightFilterSidebar';
import SmartFiltersPinned from './smartFilters/SmartFiltersPinned';
import FlightMobileFilterBar from './FlightMobileFilterBar';
import FlightsEmptyState from './FlightsEmptyState';
import FlightsSearchingState from './FlightsSearchingState';
import { NO_SEARCH_YET } from './noSearchYet';
import FlightsErrorState from './FlightsErrorState';
import { toastFlightError, toastDevUpstreamFailure } from '@/services/flights/errors.client';
import { requestFlightApproval } from '@/services/flights/approvalRequest';
import { describeFlightSelection, trackFlightEvent, trackFlightEventOnce } from '@/services/flights/tracking';
import { trackMetaPixelEventOnce } from '@/lib/meta-pixel';
import { TOAST_IDS } from '@/lib/toast';
import MultiCityFlightCard from './MultiCityFlightCard';
import MultiCityStickyBar from './MultiCityStickyBar';
import FlightFaresModal from './FlightFaresModal';

interface MultiCitySearchClientProps {
  /** Server-resolved code -> {city, country}, shown before the search API's own resolution lands. */
  initialLocationNames?: Record<string, ResolvedLocation>;
}

export default function MultiCitySearchClient({ initialLocationNames }: MultiCitySearchClientProps = {}) {
  const searchParams = useSearchParams();
  const pathname = usePathname();
  // corp: no router here any more — requesting approval does not navigate.
  const dispatch = useAppDispatch();

  const { offersResult, offersIdentity, offersStatus, offersError, offersCapped, activeSort, filters, smartPredicates, searchTrigger } =
    useAppSelector((state) => state.flightSearch);

  const [activeLeg, setActiveLeg] = useState(0);
  // One selected (flight + fare) per leg, in leg order — populated as the user
  // picks a fare on each leg's tab via MultiCityFlightCard's own inline fare rows.
  const [selectedLegs, setSelectedLegs] = useState<(FlightData | null)[]>([]);
  // Shared multi-flight fares modal (same one round-trip uses) — opened from the
  // sticky bar's Continue for a last look across every leg before handing off to
  // review/booking; that modal owns /flight-review navigation (login not required).
  const [isFaresModalOpen, setIsFaresModalOpen] = useState(false);
  // True while Continue is skipping straight to review (every leg has only
  // one fare option — nothing to actually pick in the modal).
  const [isGoingToReview, setIsGoingToReview] = useState(false);

  // Parsed once per render, reused by both effects below instead of each
  // independently re-parsing the same params.
  const legs = useMemo(
    () => parseItinerary(searchParams.get('itinerary')).map((s) => ({
      from: s.from,
      fromCity: initialLocationNames?.[s.from]?.city || s.from,
      to: s.to,
      toCity: initialLocationNames?.[s.to]?.city || s.to,
      date: s.date,
    })),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [searchParams.toString(), initialLocationNames],
  );
  useSyncSearchUrl(legs, filters);

  // One-shot: hydrate filters from a shared/bookmarked/refreshed URL — see
  // FlightsSearchClient.tsx's identical effect for why this is guarded to
  // run only once rather than folded into useSyncSearchUrl itself.
  const filtersHydratedRef = useRef(false);
  useEffect(() => {
    if (filtersHydratedRef.current) return;
    filtersHydratedRef.current = true;
    const patch = parseFiltersFromParams(searchParams);
    if (Object.keys(patch).length > 0) dispatch(setFilters(patch));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const adults = Number(searchParams.get('adults') || 1);
  const children = parseChildren(searchParams);
  const infants = parseInfants(searchParams.get('infants'));
  const cabin = decodeCabinClass(searchParams.get('cabinClass'));
  const directOnly = searchParams.get('directOnly') === 'true';

  // Serves a recent identical search from memory before asking the server —
  // see useCachedFlightSearch. A multi-city itinerary needs at least two legs
  // to be a search at all.
  const searchInput = useMemo(
    () =>
      legs.length >= 2
        ? {
            tripType: 'multicity' as const,
            legs,
            adults,
            children,
            infants,
            cabin,
            directOnly,
          }
        : null,
    [legs, adults, children, infants, cabin, directOnly],
  );

  /**
   * The store's offers, but only when they answer the search the URL is asking
   * for — see FlightsSearchClient for the full reasoning. Browser Back changes
   * the URL without going through the form, so nothing supersedes the previous
   * search's offers there; this is what keeps them off screen until the request
   * for the new URL has an answer.
   *
   * Only the offers. `offersResult.legs` keeps reading the raw result below:
   * those label the leg tabs, which are page chrome rather than answers, and
   * blanking them mid-search would collapse the layout.
   */
  const currentResult =
    searchInput !== null && offersIdentity !== null && offersIdentity === searchIdentityKey(searchInput)
      ? offersResult
      : null;

  useCachedFlightSearch({
    input: searchInput,
    searchTrigger,
    onRejected: (action) => {
      if (action.payload) {
        toastDevUpstreamFailure(action.payload, { id: TOAST_IDS.flightUpstreamDev, context: 'Flight search' });
      }
    },
  });

  // Re-runs the exact same search that just failed — same params, fresh call.
  function handleRetrySearch() {
    dispatch(fetchFlightOffers({
      tripType: 'multicity',
      legs,
      adults,
      children,
      infants,
      cabin,
      directOnly,
    }));
  }

  // New search (legs changed) — the previous run's per-leg selections no longer
  // apply, so start clean rather than carrying over stale flights/fares.
  useEffect(() => {
    setSelectedLegs(Array.from({ length: legs.length }, () => null));
    setActiveLeg(0);
  }, [legs]);

  // Server-side filter refinement: a *fallback*, not an automatic companion to
  // price/airline/refundable/bags filters. Those four are already filtered
  // correctly from whatever offers are already fetched (applyFlightFilters
  // reads outbound.checkin/refundStatus/etc. straight off each offer) — the
  // only thing a server round-trip can add is recovering matches *beyond* the
  // capped ~250-offer batch, which is only worth it when local filtering has
  // nothing to show at all. Merges into the existing set in the background
  // (see fetchFlightOffers.fulfilled reducer), so this only ever adds
  // results, never blocks the page.
  const lastRefinementKey = useRef<string | null>(null);
  useEffect(() => {
    if (legs.length < 2) return;

    // Only bother refining if the broad search actually hit the offers cap
    // (otherwise Amadeus has nothing more to give) AND local filtering left
    // nothing to show. `rawOffers` (the memoized version) isn't declared
    // until further down this component, so this reads offersResult directly.
    const currentRawOffers = currentResult?.tripType === 'multicity' ? currentResult.offers : [];
    const hasServerFilters =
      offersCapped &&
      currentRawOffers.length > 0 &&
      applyFlightFilters(currentRawOffers, filters).length === 0 &&
      (filters.maxPrice != null || filters.airlines.length > 0 || filters.refundableOnly || filters.checkedBagsOnly);
    const legsKey = legs.map((l) => `${l.from}${l.to}${l.date}`).join(',');
    const key = `${legsKey}|${adults}|${children}|${infants}|${cabin}|${directOnly}|${filters.maxPrice}|${filters.airlines.join(',')}|${filters.refundableOnly}|${filters.checkedBagsOnly}`;
    if (!hasServerFilters || lastRefinementKey.current === key) return;

    let abort: (() => void) | undefined;
    const timer = setTimeout(() => {
      lastRefinementKey.current = key;
      const promise = dispatch(fetchFlightOffers({
        tripType: 'multicity',
        legs,
        adults,
        children,
        infants,
        cabin,
        directOnly,
        maxPrice: filters.maxPrice ?? undefined,
        includedCarriers: filters.airlines.length ? filters.airlines : undefined,
        refundableOnly: filters.refundableOnly || undefined,
        includedCheckedBagsOnly: filters.checkedBagsOnly || undefined,
        isRefinement: true,
      }));
      // A refinement failure used to be swallowed entirely: the reducer returns
      // early for isRefinement, so the user silently kept an unrefined list with
      // no hint their filter never reached the server. That was the right call
      // when the only alternative was replacing the whole page with an error —
      // a dismissible toast is the proportionate weight. Handled here rather
      // than in the reducer so reducers stay pure. Aborted refinements (the
      // debounce superseding itself) are not failures and stay silent.
      promise.then((action) => {
        if (fetchFlightOffers.rejected.match(action) && !action.meta.aborted && action.payload) {
          toastFlightError(action.payload, {
            id: TOAST_IDS.flightRefinement,
            context: 'refinement search',
          });
        }
      });
      abort = () => promise.abort();
    }, 400);

    return () => {
      clearTimeout(timer);
      abort?.();
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [legs, adults, children, infants, cabin, directOnly, offersCapped, filters.maxPrice, filters.airlines.join(','), filters.refundableOnly, filters.checkedBagsOnly]);

  const isLoading = offersStatus === 'loading';
  const resultOffers = currentResult?.tripType === 'multicity' ? currentResult.offers : [];
  // See directOnlyOffers: instant narrowing while the authoritative search runs,
  // and a guarantee that a connection never appears under a direct-only search.
  const rawOffers = directOnly ? directOnlyOffers(resultOffers) : resultOffers;
  const offers = sortFlights(applySmartPredicates(applyFlightFilters(rawOffers, filters), smartPredicates), activeSort);

  // Cheapest/fastest sort tab subtext, computed from whatever's currently shown —
  // reuses the same sortFlights logic so it never drifts from the actual sort order.
  const cheapestOffer = offers.length ? sortFlights(offers, 'cheapest')[0] : null;
  const fastestOffer = offers.length ? sortFlights(offers, 'fastest')[0] : null;

  // Each offer is a single-leg (oneWay:true) offer tagged with which search leg it
  // belongs to (flightOfferAdapter sets `legIndex` from the search-service's
  // meta.oneWayCombinations) — group by that instead of re-slicing one shared
  // whole-journey offer list, so every leg tab shows that leg's own real offers
  // and pricing rather than the same combined-itinerary price repeated per tab.
  const legCount = legs.length || (offersResult?.legs?.length ?? 0);
  const perLegOffers: FlightData[][] = useMemo(() => {
    if (offers.length === 0 || legCount === 0) return [];
    const grouped: FlightData[][] = Array.from({ length: legCount }, () => []);
    for (const offer of offers) {
      if (offer.legIndex != null && offer.legIndex >= 0 && offer.legIndex < legCount) {
        grouped[offer.legIndex].push(offer);
      }
    }
    return grouped;
  }, [offers, legCount]);

  const legLabels: { label: string; date: string }[] = useMemo(() => {
    const src = offersResult?.legs ?? legs;
    return src.map((l) => ({
      label: `${l.fromCity || l.from} → ${l.toCity || l.to}`,
      date: l.date ? new Date(l.date).toLocaleDateString('en-US', { weekday: 'short', day: '2-digit', month: 'short' }) : '',
    }));
  }, [offersResult?.legs, legs]);

  const currentLegOffers = perLegOffers[activeLeg] ?? [];
  // Unfiltered, scoped to the active leg only — Smart Filters' chips and
  // context (available airlines, price range) must reflect what this leg
  // alone can return, not the whole itinerary's combined offer pool the
  // sidebar's facets are built from.
  const currentLegRawOffers = useMemo(
    () => rawOffers.filter((o) => o.legIndex === activeLeg),
    [rawOffers, activeLeg],
  );
  // Nothing to sort or filter once we know for certain the whole itinerary has
  // zero matching offers — hide both and hand the whole width to the empty state
  // (still shown during loading, since we don't know the outcome yet). This is
  // distinct from a single empty leg tab (handled below), where other legs may
  // still have real results worth sorting/filtering.
  /**
   * Same split as the one-way screen: the search finding nothing and the
   * filters excluding everything look identical in `offers.length`, but only
   * one of them is fixable from the sidebar — so only one of them may hide it.
   */
  const noResults = !isLoading && rawOffers.length === 0;
  const filteredToNothing = !isLoading && rawOffers.length > 0 && offers.length === 0;
  const isEmpty = noResults;

  // Depends on the currency string, not the offers array: `rawOffers` is rebuilt by
  // a ternary on every render, so listing it would recompute the chips every
  // time regardless of whether anything they describe had changed.
  const filterCurrency = rawOffers[0]?.currency ?? '';
  const filterChips = useMemo(
    () => describeActiveFilters(filters, { currency: filterCurrency }),
    [filters, filterCurrency],
  );
  // Nothing was searched for, so "no flights found" would be untrue — see NO_SEARCH_YET.
  const noSearchYet = legs.length < 2;
  // First paint of a search — nothing has ever come back yet, so there's no
  // list to keep visible underneath a skeleton. Same isFirstLoad gate as the
  // one-way and round-trip results pages — a filter-driven refinement of
  // results already on screen (isLoading but rawOffers.length > 0) keeps the
  // lighter skeleton treatment instead.
  const isFirstLoad = isLoading && rawOffers.length === 0;

  // Campaign funnel: results for this itinerary are on screen. One event for the whole
  // itinerary rather than one per leg tab — the traveller searched a trip, not N trips —
  // keyed on the search so switching leg tabs, sorting or filtering does not re-report it.
  useEffect(() => {
    if (offersStatus !== 'success' || offersResult?.tripType !== 'multicity') return;
    const search = searchParams.toString();
    const first = legs[0];
    const last = legs[legs.length - 1];
    void trackFlightEventOnce(
      `multicity:${search}`,
      'SRP_LISTINGS_VIEWED',
      {
        originLocationCode: first?.from,
        destinationLocationCode: last?.to,
        departureDate: first?.date,
        tripType: 'MULTICITY',
      },
      {
        metadata: {
          path: pathname,
          search,
          totalListings: rawOffers.length,
          visibleListings: offers.length,
          legCount: legs.length,
          legs: legs.map((l) => `${l.from}-${l.to}`),
          cabin,
          directOnly,
          adults,
          children,
          infants,
        },
      }
    );
    return trackMetaPixelEventOnce(`Search:flights:${search}`, 'Search', {
      search_string: legs.map((l) => `${l.from}-${l.to} ${l.date}`).join(', '),
      content_type: 'product',
      content_category: 'Flight',
      value: offers[0]?.pricePerPerson ?? 0,
      currency: offers[0]?.currency ?? 'USD',
    });
  // Derived counts are read for context only; the dedupe key is the search itself.
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [offersStatus, offersResult, searchParams, pathname]);

  function handleSelectLeg(flight: FlightData) {
    setSelectedLegs((prev) => prev.map((l, i) => (i === activeLeg ? flight : l)));
  }

  function handleNextLeg() {
    setActiveLeg((prev) => Math.min(prev + 1, legCount - 1));
  }

  // Sticky bar "Continue" (only shown once every leg has a selection) opens the
  // shared multi-flight fares modal for a last look across all legs together —
  // the actual navigate-to-review handoff happens from *that* modal's own
  // Continue, same as round-trip.
  // Skipped when every leg has exactly one fare option: there's nothing to
  // actually choose between, so this goes straight to review instead.
  async function handleContinue() {
    if (isGoingToReview) return;
    const chosenFlights = selectedLegs.filter((l): l is FlightData => l !== null);

    // The multi-city equivalent of singling out a card: every leg now has a chosen flight.
    void trackFlightEvent('SEE_AVAILABILITY_CLICK', describeFlightSelection(chosenFlights, 'MULTICITY'), {
      revenueAmount: chosenFlights.reduce((total, f) => total + (f.pricePerPerson ?? 0), 0) || undefined,
      currency: chosenFlights[0]?.currency,
      metadata: { offerIds: chosenFlights.map((f) => f.id), legCount: chosenFlights.length },
    });

    const onlyOneFareEach =
      chosenFlights.length > 0 && chosenFlights.every((l) => (l.fareOptions?.length ?? 0) === 1);
    if (onlyOneFareEach) {
      setIsGoingToReview(true);
      // corp: every leg has a single fare, so there is nothing to pick —
      // request approval directly. leisure-ui booked here instead.
      const ok = await requestFlightApproval({ flights: chosenFlights, tripType: 'MULTICITY' });
      if (!ok) setIsGoingToReview(false);
      return;
    }
    setIsFaresModalOpen(true);
  }

  function handleFaresSelected() {
    // Each leg's raw Amadeus flightOffer, untouched — search-service already
    // gave us this exact shape, so this is what Price/booking should receive.
    const rawOffers = selectedLegs
      .filter((l): l is FlightData => l !== null)
      .map((l) => l._rawOffer);
    console.log('[MultiCity] selected flight-offers (raw Amadeus shape):', rawOffers);
  }

  return (
    <>
      <div className="row g-3">
        {/* Phone only. Below lg the filter column is ordered after the whole
            list, so this is how filters and sort are reached there. */}
        {!isEmpty && !isFirstLoad && currentLegRawOffers.length > 0 && legs[activeLeg] && (
          <div className="col-12 order-0 d-lg-none">
            <SmartFiltersPinned
              offers={currentLegRawOffers}
              filters={filters}
              activeSort={activeSort}
              tripType="multicity"
              origin={legs[activeLeg].from}
              destination={legs[activeLeg].to}
              departDate={legs[activeLeg].date}
              legIndex={activeLeg}
              currency={currentLegRawOffers[0]?.currency ?? ''}
            />
          </div>
        )}
        {!isEmpty && !isFirstLoad && (
          <FlightMobileFilterBar
            offers={rawOffers}
            resultCount={offers.length}
            totalCount={rawOffers.length}
            searchContext={legs[activeLeg] ? {
              tripType: 'multicity',
              origin: legs[activeLeg].from,
              destination: legs[activeLeg].to,
              departDate: legs[activeLeg].date,
              legIndex: activeLeg,
              currency: rawOffers[0]?.currency ?? '',
            } : undefined}
          />
        )}

        {!isEmpty && !isFirstLoad && (
          <div className="col-12 order-1">
            <h3 className="text-xxl color-text-dark fw-semibold mb-0 pt-2">
              {isLoading ? 'Searching...' : `${offers.length}${rawOffers.length !== offers.length ? ` of ${rawOffers.length}` : ''} multi-city itineraries found`}
            </h3>
            <p className="mb-0 text-sm">
              {legLabels.map((l) => l.label).join(' · ')}
            </p>
            {offersError && <p className="text-danger text-sm mt-1">{offersError.message}</p>}
            <FlightSortTabs
              activeTab={activeSort}
              onTabChange={(tab) => dispatch(setActiveSort(tab as SortKey))}
              cheapestLabel={cheapestOffer ? `${cheapestOffer.currency}${cheapestOffer.pricePerPerson}` : undefined}
              fastestLabel={fastestOffer?.outbound.duration}
            />
          </div>
        )}

        {isFirstLoad ? (
          <div className="col-12 order-2">
            <FlightsSearchingState routeLabel={legLabels.map((l) => l.label).join(' · ')} />
          </div>
        ) : isEmpty ? (
          <div className="col-12 order-2">
            {offersError ? (
              <FlightsErrorState error={offersError} onRetry={handleRetrySearch} />
            ) : noSearchYet ? (
              <FlightsEmptyState title={NO_SEARCH_YET.title} description={NO_SEARCH_YET.description} />
            ) : (
              <FlightsEmptyState />
            )}
          </div>
        ) : (
        <>
        <div className="col-xxl-3 col-xl-3 col-lg-3 col-md-12 col-12 order-lg-2 order-3 filterDetails sticky-filter-sidebar position-sticky top-0 mb-3 mb-lg-0 d-none d-lg-block">
          <FlightFilterSidebar
            offers={rawOffers}
            onClearFilters={() => dispatch(resetFilters())}
            isLoading={isLoading}
            smartFiltersContext={legs[activeLeg] ? {
              tripType: 'multicity',
              origin: legs[activeLeg].from,
              destination: legs[activeLeg].to,
              departDate: legs[activeLeg].date,
              legIndex: activeLeg,
              currency: rawOffers[0]?.currency ?? '',
            } : undefined}
          />
        </div>

        <div className="col-lg-9 col-md-12 col-sm-12 col-12 order-lg-3 order-2">

          {/* Leg tabs — stretched to fill the row and read as one connected
              bar, not separate pills (see .top-flight-legs-tabs in
              custom-fixes.css); wraps to a second line rather than
              scrolling or squishing when there are more legs than fit. */}
          <div className="nav nav-pills flight-legs-tabs top-flight-legs-tabs mb-3 flex-wrap" role="tablist">
            {legLabels.map((leg, i) => (
              <button
                key={i}
                className={`nav-link w-250 border p-2 text-center d-flex flex-column gap-1${activeLeg === i ? ' active' : ''}`}
                type="button"
                role="tab"
                onClick={() => setActiveLeg(i)}
              >
                <span className="text-md fw-600 color-text-dark">{leg.label}</span>
                <span className="text-sm color-text-dark">{leg.date}</span>
                {selectedLegs[i] && (
                  <span className="text-xs color-text-second fw-600">Selected ✓</span>
                )}
              </button>
            ))}
          </div>

          {/* Current leg results */}
          {isLoading ? (
            <div className="d-flex flex-column gap-3">
              {Array.from({ length: 4 }).map((_, k) => (
                <div key={k} className="card rounded-3 bgColor-white p-3" style={{ height: 130 }}>
                  <div className="skeleton-box w-100 h-100 rounded-2" style={{ backgroundColor: '#dee2e6' }} />
                </div>
              ))}
            </div>
          ) : filteredToNothing ? (
            // Every leg is empty because of the filters, not because the route
            // has nothing — so this replaces the per-leg message, which would
            // otherwise blame the leg for something the sidebar caused.
            <FlightsFilteredEmptyState
              totalBeforeFilters={rawOffers.length}
              chips={filterChips}
              onRemove={(chip: ActiveFilterChip) => dispatch(setFilters(chip.reset))}
              onClearAll={() => dispatch(resetFilters())}
              offers={rawOffers}
              filters={filters}
              currency={filterCurrency}
              onRelax={(patch) => dispatch(setFilters(patch))}
            />
          ) : currentLegOffers.length === 0 ? (
            // Other legs still have results, so this really is about this leg.
            <FlightsEmptyState title="No flights found for this leg" />
          ) : (
            <div className="d-flex flex-column gap-3">
              {currentLegOffers.map((flight, i) => (
                <MultiCityFlightCard
                  key={flight.id + '-' + activeLeg}
                  flight={flight}
                  index={i}
                  isSelected={selectedLegs[activeLeg]?.id === flight.id}
                  onSelect={handleSelectLeg}
                />
              ))}
            </div>
          )}
        </div>
        </>
        )}
      </div>

      {selectedLegs.some((l) => l !== null) && (
        <MultiCityStickyBar
          selectedLegs={selectedLegs}
          activeLeg={activeLeg}
          totalLegs={legCount}
          onNext={handleNextLeg}
          onContinue={handleContinue}
          continuing={isGoingToReview}
        />
      )}

      {isFaresModalOpen && (
        <FlightFaresModal
          isOpen={isFaresModalOpen}
          onClose={() => setIsFaresModalOpen(false)}
          flights={selectedLegs.filter((l): l is FlightData => l !== null)}
          flightLabels={legLabels.map((l) => l.label)}
          tripType="MULTICITY"
          onSelectFares={handleFaresSelected}
        />
      )}
    </>
  );
}
