'use client';

import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { fetchFlightOffers, setActiveSort, resetFilters, setFilters, applyFlightFilters, sortFlights, searchCacheKey, searchIdentityKey } from '@/store/slices/flightSearch.slice';
import { applySmartPredicates } from '@/services/flights/smartFilters/applySmartPredicates';
import type { SortKey } from '@/store/slices/flightSearch.slice';
import { describeActiveFilters, directOnlyOffers, type ActiveFilterChip } from '@/services/flights/filterSort';
import { parseItinerary, parseChildren, parseInfants, decodeCabinClass, rememberFlightSearchUrl } from '@/services/flights/searchUrl';
import { parseFiltersFromParams } from '@/services/flights/filtersUrl';
import { useSyncSearchUrl } from './useSyncSearchUrl';
import { useCachedFlightSearch } from './useCachedFlightSearch';
import { useCompareTray } from './useCompareTray';
import CompareTray from './CompareTray';
import { buildCompareUrl } from '@/services/flights/compareUrl';
import type { ResolvedLocation } from '@/services/flights/resolveFlightCityNames';
import FlightSortTabs from './FlightSortTabs';
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 { TOAST_IDS } from '@/lib/toast';
import FlightsList from './FlightsList';
import FlightDateStrip from './FlightDateStrip';
import FlightsFilteredEmptyState from './FlightsFilteredEmptyState';
import { AwaitingReturnDateNotice, SearchFailedNotice } from './FlightResultsNotice';
import { trackFlightEventOnce } from '@/services/flights/tracking';
import { trackMetaPixelEventOnce } from '@/lib/meta-pixel';

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

export default function FlightsSearchClient({ initialLocationNames }: FlightsSearchClientProps = {}) {
  const dispatch = useAppDispatch();
  const searchParams = useSearchParams();
  const pathname = usePathname();

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

  const directOnly = searchParams.get('directOnly') === 'true';

  const isLoading = offersStatus === 'loading';

  // Parsed once per render, reused by both effects below instead of each
  // independently re-parsing the same params.
  const segments = parseItinerary(searchParams.get('itinerary'));

  // One-shot: hydrate filters from a shared/bookmarked/refreshed URL. Guarded
  // so it only ever runs once per mount — after that, useSyncSearchUrl above
  // is the only thing writing to these params, and re-reading them on every
  // navigation would fight its own writes.
  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 fromCode = segments[0]?.from ?? '';
  const toCode = segments[0]?.to ?? '';
  const departDate = segments[0]?.date ?? '';
  // Passed through to the thunk so the slice's own city-name resolution (which only
  // covers codes that appear as real segments in the search response — grouping codes
  // like "LON" never do) has a good fallback instead of silently reverting to the raw code.
  const fromCity = initialLocationNames?.[fromCode]?.city || fromCode;
  const toCity = initialLocationNames?.[toCode]?.city || toCode;
  const adults = Number(searchParams.get('adults') ?? 1);
  const children = parseChildren(searchParams);
  const infants = parseInfants(searchParams.get('infants'));
  const cabin = decodeCabinClass(searchParams.get('cabinClass'));

  // Serves a recent identical search from memory before asking the server —
  // see useCachedFlightSearch for the age rules. `null` while the URL does not
  // yet describe a complete search.
  const searchInput = useMemo(
    () =>
      fromCode && toCode && departDate
        ? {
            tripType: 'oneway' as const,
            from: fromCode,
            fromCity,
            to: toCode,
            toCity,
            departDate,
            adults,
            children,
            infants,
            cabin,
            directOnly,
          }
        : null,
    [fromCode, toCode, fromCity, toCity, departDate, adults, children, infants, cabin, directOnly],
  );

  useSyncSearchUrl(segments, filters);

  /**
   * Whether what is in the store answers the search the URL is asking for.
   *
   * Derived at render rather than waited for, because the URL changes a beat
   * before the request that follows it does: for that beat the previous
   * search's offers were still on screen under a form that already said
   * something else — Economy fares sitting under a Business cabin. The store's
   * own pending reducer drops them too, but only once the thunk starts.
   *
   * Direct-only is deliberately not part of this (see searchIdentityKey): it
   * narrows the same inventory, and the optimistic filter below is what makes
   * the toggle feel instant.
   */
  const resultsAnswerThisSearch =
    searchInput !== null && offersIdentity !== null && offersIdentity === searchIdentityKey(searchInput);

  const resultOffers =
    resultsAnswerThisSearch && offersResult?.tripType === 'oneway' ? offersResult.offers : [];
  // Narrowed the moment the toggle flips, before the authoritative direct-only
  // search returns — and a standing guarantee that nothing with a connection
  // appears under one. See directOnlyOffers.
  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;

  const router = useRouter();

  // Owns the compare tray for this search — binds it, restores it, mirrors it.
  // The cards read the same store directly (useCompareEntry) rather than
  // receiving props through the virtualised list.
  const compare = useCompareTray({
    searchKey: searchInput ? searchCacheKey(searchInput) : null,
    step: 'outbound',
  });

  const openCompare = useCallback(() => {
    const href = buildCompareUrl({
      searchParams: new URLSearchParams(searchParams.toString()),
      sliceKeys: compare.entries.map((e) => e.sliceKey),
      step: 'outbound',
    });
    // A new tab on a pointer device, so the results the traveller spent time
    // filtering are still there behind it. A phone has no useful second tab,
    // so it opens in place and the Back button does the work.
    const isTouch =
      typeof window !== 'undefined' &&
      !window.matchMedia('(hover: hover) and (pointer: fine)').matches;
    if (isTouch) router.push(href);
    else window.open(href, '_blank', 'noopener,noreferrer');
  }, [compare.entries, searchParams, router]);

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

  // Remember this as the traveller's last real search — see
  // rememberFlightSearchUrl's own comment for why "Book Another Flight" needs it.
  useEffect(() => {
    if (!fromCode || !toCode || !departDate) return;
    rememberFlightSearchUrl('/srp/flights', searchParams.toString());
  }, [fromCode, toCode, departDate, searchParams]);

  // Campaign funnel: results for this search are on screen. Keyed on the search itself,
  // so the things that re-run this effect without changing what was searched for — a sort
  // tab, a client-side filter, the background refinement merging more offers into the same
  // result set — report one exposure rather than five. A new date from the date strip is a
  // new search and does report again.
  useEffect(() => {
    if (offersStatus !== 'success' || !offersResult || offersResult.tripType !== 'oneway') return;
    const search = searchParams.toString();
    void trackFlightEventOnce(
      `oneway:${search}`,
      'SRP_LISTINGS_VIEWED',
      {
        originLocationCode: fromCode,
        destinationLocationCode: toCode,
        departureDate: departDate,
        tripType: 'ONEWAY',
      },
      {
        metadata: {
          path: pathname,
          search,
          totalListings: rawOffers.length,
          visibleListings: offers.length,
          cabin,
          directOnly,
          adults,
          children,
          infants,
        },
      }
    );
    // Meta's own Search event, same moment and same key. Only reports for visitors Meta
    // attribution is active for (utm_source=meta) — the existing gate on every pixel event
    // in the app, hotels included.
    return trackMetaPixelEventOnce(`Search:flights:${search}`, 'Search', {
      search_string: `${fromCode}-${toCode} ${departDate}`,
      content_type: 'product',
      content_category: 'Flight',
      value: offers[0]?.pricePerPerson ?? 0,
      currency: offers[0]?.currency ?? 'USD',
    });
  // offers/rawOffers are derived on every render; the dedupe key is the search, so they
  // are read here but deliberately not depended on.
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [offersStatus, offersResult, searchParams, pathname]);

  // Re-runs the exact same search that just failed — same params, fresh call.
  function handleRetrySearch() {
    dispatch(fetchFlightOffers({
      tripType: 'oneway',
      from: fromCode,
      fromCity,
      to: toCode,
      toCity,
      departDate,
      adults,
      children,
      infants,
      cabin,
      directOnly,
    }));
  }

  // 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. That's only worth doing when local filtering has
  // nothing to show; when it already has real results, showing those instantly
  // is better than a background network call the traveller didn't ask for.
  // Runs as a background merge (see fetchFlightOffers.fulfilled reducer) so
  // this only ever adds to what's shown, never blocks it. Debounced so
  // dragging the price slider doesn't fire a request per pixel.
  const lastRefinementKey = useRef<string | null>(null);
  const [isRefining, setIsRefining] = useState(false);
  useEffect(() => {
    if (!fromCode || !toCode || !departDate) 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 — a capped search with a thin-but-nonempty local match
    // is left alone rather than topped up in the background.
    const hasServerFilters =
      offersCapped &&
      rawOffers.length > 0 &&
      offers.length === 0 &&
      (filters.maxPrice != null || filters.airlines.length > 0 || filters.refundableOnly || filters.checkedBagsOnly);
    const key = `${fromCode}|${toCode}|${departDate}|${adults}|${children}|${infants}|${cabin}|${directOnly}|${filters.maxPrice}|${filters.airlines.join(',')}|${filters.refundableOnly}|${filters.checkedBagsOnly}`;
    if (!hasServerFilters || lastRefinementKey.current === key) return;

    let abort: (() => void) | undefined;
    // A refinement deliberately does not set offersStatus (see the slice's
    // pending case) so results never flash — which means isLoading is false
    // while it runs. Without knowing about it, the filtered-empty state would
    // announce "no flights match" a second before the matches it is fetching
    // arrive. Tracked locally rather than in the store because it describes
    // this screen's own request, not the search.
    setIsRefining(true);
    const timer = setTimeout(() => {
      lastRefinementKey.current = key;
      const promise = dispatch(fetchFlightOffers({
        tripType: 'oneway',
        from: fromCode,
        fromCity,
        to: toCode,
        toCity,
        departDate,
        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) => {
        // `aborted` lives only on the rejected variant, so it has to be read
        // through the matcher. An abort means a newer refinement is already in
        // flight and has set the flag again — clearing it here would blink the
        // empty state between two debounced requests.
        const wasAborted = fetchFlightOffers.rejected.match(action) && action.meta.aborted;
        if (!wasAborted) setIsRefining(false);
        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
  }, [fromCode, toCode, fromCity, toCity, departDate, adults, children, infants, cabin, directOnly, offersCapped, filters.maxPrice, filters.airlines.join(','), filters.refundableOnly, filters.checkedBagsOnly]);

  // Applying a filter can shrink the list to fewer rows than the user has
  // already scrolled past — e.g. picking an airline with 2 flights while scrolled
  // down near the footer leaves them stranded below the results. When the filter
  // set changes, if the results block has scrolled above the viewport, pull its
  // top back into view. Skips the first run (initial filters) and only nudges
  // when the user is actually past the top, so it never yanks the page otherwise.
  const contentRef = useRef<HTMLDivElement>(null);
  const filterSignature = JSON.stringify(filters);
  const filterScrollPrimed = useRef(false);
  useEffect(() => {
    if (!filterScrollPrimed.current) {
      filterScrollPrimed.current = true;
      return;
    }
    const el = contentRef.current;
    if (!el) return;
    const top = el.getBoundingClientRect().top;
    if (top < 0) {
      window.scrollTo({ top: window.scrollY + top - 90, behavior: 'smooth' });
    }
  }, [filterSignature]);

  const origin = offersResult?.fromCity || initialLocationNames?.[fromCode]?.city || fromCode || '—';
  const dest   = offersResult?.toCity   || initialLocationNames?.[toCode]?.city   || toCode   || '—';
  const date   = offersResult?.departureDate ?? departDate;
  const dateLabel = date
    ? new Date(date).toLocaleDateString('en-US', { weekday: 'short', day: '2-digit', month: 'short' })
    : '';
  // Nothing to sort or filter once we know for certain there are zero results —
  // hide both and hand the whole width to the empty state (still shown during
  // loading, since we don't know the outcome yet).
  /**
   * Two different empties, and the difference decides the whole layout.
   *
   * `noResults` is the search itself coming back with nothing: there is nothing
   * to filter, so the sidebar has no purpose and the empty state takes the full
   * width. `filteredToNothing` is the search having found flights that the
   * current filters exclude — the sidebar is then the *only* way out, and
   * hiding it (which is what a single `offers.length === 0` test did) removed
   * the control the traveller needed to undo what they had just done.
   */
  const noResults = !isLoading && rawOffers.length === 0;
  const filteredToNothing = !isLoading && rawOffers.length > 0 && offers.length === 0;
  /** Full-width empty state: only when filtering is not the cause. */
  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 = !fromCode || !toCode || !departDate;
  // First paint of a search — nothing has ever come back yet, so there's no
  // list to keep visible underneath a skeleton. A filter-driven REFINEMENT
  // of results already on screen (isLoading but rawOffers.length > 0)
  // deliberately keeps the lighter skeleton treatment below instead —
  // swapping the whole page out on every filter click would be worse, not
  // better.
  const isFirstLoad = isLoading && rawOffers.length === 0;

  /**
   * The strip is hidden while the first results are still being fetched — a
   * row of dates above a searching state is navigation for a page that has not
   * arrived yet. After that it stays, including while a later search runs:
   * clicking a date in the strip reloads the results, and having the control
   * you just used blink out from under the cursor and back is worse than a
   * moment of stale-looking dates. It reads its selected date from the URL, so
   * it is already correct the instant the navigation happens.
   */
  const hasShownResults = useRef(false);
  useEffect(() => {
    if (rawOffers.length > 0) hasShownResults.current = true;
  }, [rawOffers.length]);
  /**
   * `idle` counts as waiting, not as "done with nothing".
   *
   * On the server `offersStatus` is idle — the search is dispatched from an
   * effect, so it has not started yet — and testing only `isLoading` rendered
   * the strip into the SSR markup, then tore it out the instant the client
   * began fetching and put it back when results landed. Two flashes before the
   * page had shown anything.
   *
   * A finished search with zero results deliberately still shows the strip:
   * that is precisely when a nearby date is the most useful thing on screen.
   */
  const awaitingFirstResults = (offersStatus === 'idle' || isLoading) && rawOffers.length === 0;
  const showDateStrip = !awaitingFirstResults || hasShownResults.current;


  return (
    <div className="row g-3" ref={contentRef}>
      {/* Phone only, and only once there is something to refine — a bar over
          an empty state offers filters for nothing. */}
      {!isEmpty && !isFirstLoad && rawOffers.length > 0 && (
        <div className="col-12 order-0 d-lg-none">
          <SmartFiltersPinned
            offers={rawOffers}
            filters={filters}
            activeSort={activeSort}
            tripType="oneway"
            origin={fromCode}
            destination={toCode}
            departDate={departDate}
            currency={filterCurrency}
          />
        </div>
      )}
      {!isEmpty && !isFirstLoad && (
        <FlightMobileFilterBar
          offers={rawOffers}
          resultCount={offers.length}
          totalCount={rawOffers.length}
          searchContext={{
            tripType: 'oneway',
            origin: fromCode,
            destination: toCode,
            departDate,
            currency: filterCurrency,
          }}
        />
      )}

      {/* Above the empty-state branch on purpose: a date that returns nothing
          is exactly when the strip matters most — it is the only way off this
          date without going back to the form. */}
      <div className="col-12 order-0 flight-date-strip-col">
        {showDateStrip && <FlightDateStrip tripType="oneway" />}
      </div>

      {!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}` : ''} flights found`}
          </h3>
          <p className="mb-0 text-sm">
            {origin} to {dest}{dateLabel ? ` · ${dateLabel}` : ''}
          </p>

          <FlightSortTabs
            activeTab={activeSort}
            onTabChange={(tab) => dispatch(setActiveSort(tab as SortKey))}
            cheapestLabel={cheapestOffer ? `${cheapestOffer.currency}${cheapestOffer.pricePerPerson}` : undefined}
            fastestLabel={fastestOffer?.outbound.duration}
          />
        </div>
      )}

      <CompareTray
        entries={compare.entries}
        minimised={compare.minimised}
        onToggleMinimised={compare.setMinimised}
        onRemove={compare.remove}
        onClear={compare.clear}
        onCompare={openCompare}
      />

      {/*
        Above the list, not in place of it. A round trip waiting for its return
        date and a search that just failed both leave the previous results as
        the best answer on screen; replacing them would take away something the
        traveller is still using.
      */}
      {(awaitingReturnDate || (offersError && !isEmpty)) && (
        <div className="col-12 order-1">
          {awaitingReturnDate ? <AwaitingReturnDateNotice /> : null}
          {offersError && !isEmpty ? (
            <SearchFailedNotice error={offersError} onRetry={handleRetrySearch} isRetrying={isLoading} />
          ) : null}
        </div>
      )}

      {isFirstLoad ? (
        <div className="col-12 order-2">
          <FlightsSearchingState routeLabel={`${origin} to ${dest}${dateLabel ? ` · ${dateLabel}` : ''}`} />
        </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>
      ) : (
        <>
          {/* Below lg this column is ordered after the whole list, so the
              sidebar is hidden there and FlightMobileFilterBar carries the
              same controls in a bottom bar and drawer instead. Kept in the
              DOM rather than duplicated: one filter implementation, two
              places to reach it. */}
          <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={{
                tripType: 'oneway',
                origin: fromCode,
                destination: toCode,
                departDate,
                currency: filterCurrency,
              }}
            />
          </div>

          <div className="col-lg-9 col-md-12 col-sm-12 col-12 order-lg-3 order-2">
            {filteredToNothing ? (
              // A refinement for these exact filters is still running, and it
              // only ever *adds* matching offers — so there may be matches
              // arriving. Saying "none match" now would be a claim we are about
              // to contradict.
              isRefining ? (
                <FlightsSearchingState routeLabel={`${origin} to ${dest}${dateLabel ? ` · ${dateLabel}` : ''}`} />
              ) : (
                <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))}
                />
              )
            ) : (
              <FlightsList flights={offers} isLoading={isLoading} />
            )}
          </div>
        </>
      )}
    </div>
  );
}

