'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import {
  useFlightLocationSearch,
  type FlightLocationResult,
  type FlightNearbyAirport,
} from '@/hooks/useFlightLocationSearch';
import type { FlightLocationData } from '@/services/flights/search.types';
import {
  clearRecentAirports,
  pushRecentAirport,
  readRecentAirports,
  type RecentAirport,
} from '@/services/flights/recentAirports';
import { rememberLocationName } from '@/services/flights/locationNames.client';
import { departuresFor, POPULAR_DESTINATIONS, type PopularAirport } from '@/constants/popular-airports';
import { ORIGIN_COOKIE, parseOriginCookie } from '@/services/flights/originCookie';
import { getCookie } from '@/utils/cookies';
import { toTitleCase } from './displayText';
import { DepartIcon, ArriveIcon, ChevronIcon, CornerIcon, SearchSmallIcon, ClearSmallIcon } from './icons';

/** Radius the hook asks for; repeated in the label so the number is never guessed at. */
const NEARBY_RADIUS_KM = 200;

/**
 * A suggestion row. Recents and curated airports are the same shape on screen —
 * a code, a place and an airport name — so they render through one component.
 */
interface SuggestionRow {
  code: string;
  city: string;
  country: string;
  name?: string;
}

interface FsAirportFieldV3Props {
  /**
   * Which half of the journey this field is. Decides what the panel offers
   * before anything is typed: where this market's travellers fly *from*, or
   * where they fly *to*. Defaults to origin so an un-migrated call site is
   * still sensible.
   */
  role?: 'origin' | 'destination';
  /**
   * The other field's IATA code. Filtered out of the suggestions, because an
   * itinerary that starts and ends at the same airport is not a search.
   */
  excludeCode?: string;
  /** `data-dd` hook the stylesheet and the mockup both key off. */
  dd: string;
  label: string;
  icon?: 'depart' | 'arrive';
  value: FlightLocationData;
  onChange: (value: FlightLocationData) => void;
  /** Controlled: the form keeps exactly one field open at a time. */
  open: boolean;
  onOpenChange: (open: boolean) => void;
  inputId?: string;
  /**
   * A problem with the current selection, shown in place of the type-to-search
   * prompt. Used for the one case the field itself can't prevent: a destination
   * that matches the origin.
   */
  note?: string;
}

/**
 * The place an airport serves, which is what a traveller is picking.
 *
 * Amadeus's `name` is the airport's own name and frequently is not a place at
 * all: CJB comes back as "INTERNATIONAL", with "COIMBATORE" in `cityName`.
 * `name` is only the fallback for the rare entry with no city.
 */
function placeName(loc: { cityName?: string | null; name: string }): string {
  return toTitleCase(loc.cityName || loc.name);
}

/**
 * The airport's own name, or '' when it only repeats the city.
 *
 * "Madurai / Madurai" is noise; "Coimbatore / International" is the useful
 * pairing this exists for. Compared case-insensitively on the raw values,
 * before title-casing, since both arrive upper-cased.
 */
function airportName(loc: { cityName?: string | null; name: string }): string {
  const city = (loc.cityName || '').trim().toLowerCase();
  const name = (loc.name || '').trim().toLowerCase();
  // No city at all means `name` is already standing in as the place above, so
  // repeating it underneath says nothing.
  if (!name || !city || name === city) return '';
  return toTitleCase(loc.name);
}

/** Human-readable name for a result: "Coimbatore, India". */
function primaryDisplayName(loc: FlightLocationResult): string {
  const city = placeName(loc);
  const country = loc.countryName ? toTitleCase(loc.countryName) : '';
  return country ? `${city}, ${country}` : city;
}

/** Second line: the airport's own name, or "All airports of X" for a city entry. */
function primarySubtitle(loc: FlightLocationResult): string {
  if (loc.subType === 'CITY') return `All airports of ${placeName(loc)}`;
  // `name` is the clean field — detailedName is raw ("NEW YORK/NY/US:JOHN F KENNEDY").
  return airportName(loc);
}

/**
 * One suggestion, drawn exactly like an autocomplete result.
 *
 * Deliberately the same markup as `.fs-airport-main` above: typing turns this
 * list into that one, and a row that changed shape mid-interaction would read
 * as the panel being replaced rather than filtered.
 */
function SuggestionItem({ row, onSelect }: { row: SuggestionRow; onSelect: (row: SuggestionRow) => void }) {
  return (
    <div
      className="fs-airport-main"
      role="button"
      tabIndex={0}
      onClick={(e) => {
        e.stopPropagation();
        onSelect(row);
      }}
      onKeyDown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          onSelect(row);
        }
      }}
    >
      <div className="fs-code">{row.code}</div>
      <div>
        {/* No toTitleCase here: curated entries are authored in the right case
            and recents were normalised when they were stored. Applying it again
            would only reintroduce the apostrophe damage it causes. */}
        <div className="fs-ap-name fs-ap-city">
          {row.city}{row.country ? `, ${row.country}` : ''}
        </div>
        {row.name && <div className="fs-ap-sub">{row.name}</div>}
      </div>
    </div>
  );
}

/**
 * Origin / destination field for the v3 flight search.
 *
 * Clicking anywhere in the box opens a panel that carries its own search box at
 * the top, auto-focused — the pattern MakeMyTrip and most OTAs use.
 *
 * This replaces an earlier design where the field *was* the input: opening it
 * swapped the selected value for a text box in place. That was chosen to match
 * the v3 hotel destination field and to avoid a "which box am I typing in"
 * beat. What tipped it the other way is the suggestion panel: once opening the
 * field offers recents and popular airports, the selected value has to stay
 * readable while you look at them — under in-place editing it became the
 * input's placeholder and vanished the moment you typed. A separate search box
 * also gives the query somewhere to live that is bigger than one line of a
 * grid cell.
 *
 * Note this now differs from the hotel destination field, which still edits in
 * place. Worth reconciling, but as one deliberate change to both forms rather
 * than as a side effect of this one.
 *
 * Results keep the shape the design already drew for them: a city/airport as
 * the main row, and the airports within range of it as indented rows under it.
 */
export default function FsAirportFieldV3({
  role = 'origin',
  excludeCode,
  dd,
  label,
  icon = 'depart',
  value,
  onChange,
  open,
  onOpenChange,
  inputId,
  note,
}: FsAirportFieldV3Props) {
  const inputRef = useRef<HTMLInputElement>(null);
  const { searchTerm, setSearchTerm, results, isLoading, clearResults } = useFlightLocationSearch({
    debounceMs: 300,
    minChars: 2,
    // search-service caps this at 20 (Amadeus's own page size for this
    // endpoint); asking for fewer than that clips genuine keyword matches —
    // "london" alone has 20 across UK/Canada/US/South Africa.
    limit: 20,
    nearbyRadius: NEARBY_RADIUS_KM,
    nearbyLimit: 5,
  });

  /**
   * Recents and the visitor's country are read from the browser, so both start
   * empty and fill in after mount. Reading them during render would make the
   * server and the first client pass disagree — the dropdown is in the SSR
   * markup (CSS hides it until the field is open), so a mismatch here is a real
   * hydration error, not a theoretical one.
   */
  const [recents, setRecents] = useState<RecentAirport[]>([]);
  const [countryCode, setCountryCode] = useState<string | null>(null);

  useEffect(() => {
    setCountryCode(parseOriginCookie(getCookie(ORIGIN_COOKIE))?.countryCode ?? null);
  }, []);

  // Re-read on every open, not just on mount: picking an airport in the other
  // field writes to the same list, and a panel showing yesterday's history
  // while the field next to it just added an entry looks broken.
  useEffect(() => {
    if (open) setRecents(readRecentAirports());
  }, [open]);

  const curated: PopularAirport[] = useMemo(
    () => (role === 'origin' ? departuresFor(countryCode) : POPULAR_DESTINATIONS),
    [role, countryCode],
  );

  /**
   * What the panel shows before anything is typed.
   *
   * The other field's airport is filtered out of both lists — offering the
   * origin as a destination is offering a search that cannot run. Recents are
   * filtered out of the curated list too, so a frequently used airport appears
   * once, at the top, rather than twice in two sections.
   */
  const { recentRows, curatedRows } = useMemo(() => {
    const exclude = new Set([excludeCode?.toUpperCase(), value.code?.toUpperCase()].filter(Boolean) as string[]);
    const recentRows: SuggestionRow[] = recents.filter((a) => !exclude.has(a.code.toUpperCase()));
    const taken = new Set(recentRows.map((a) => a.code.toUpperCase()));
    const curatedRows: SuggestionRow[] = curated.filter(
      (a) => !exclude.has(a.code.toUpperCase()) && !taken.has(a.code.toUpperCase()),
    );
    return { recentRows, curatedRows };
  }, [recents, curated, excludeCode, value.code]);

  // Opening hands focus straight to the input — the click that opened the field
  // is the same gesture that should start typing.
  useEffect(() => {
    if (open) {
      requestAnimationFrame(() => inputRef.current?.focus());
    } else {
      setSearchTerm('');
      clearResults();
    }
    // setSearchTerm/clearResults are stable; re-running on them would wipe the
    // term on every keystroke.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  /**
   * The one place a selection is made, whichever row produced it.
   *
   * `recent` is passed separately rather than derived from `value` because the
   * two need different casing and only one of them can be normalised here.
   * Amadeus returns ALL CAPS, which is what toTitleCase exists to fix; the
   * curated suggestions are authored in the right case already, and putting
   * them through it would actively damage them ("O'Hare" -> "O'hare", since it
   * capitalises per whitespace-delimited word). So each call site hands over a
   * display-ready record and this function stores it verbatim.
   */
  const commit = (next: FlightLocationData, recent: RecentAirport) => {
    pushRecentAirport(recent);
    // The pick is the one moment this page is certain what the code is called.
    // Remembering it here is what lets the next page render "London" instead of
    // "Lhr" while its own lookup is still in flight — see locationNames.client.
    rememberLocationName(next);
    // Close before notifying: onChange is what hands focus to the next field,
    // and under a single shared "which field is open" state, closing afterwards
    // would immediately undo the field the parent just opened.
    onOpenChange(false);
    onChange(next);
  };

  const selectPrimary = (loc: FlightLocationResult) => {
    const city = loc.cityName || loc.name;
    const country = loc.countryName || '';
    commit(
      { destination: city, code: loc.iataCode, country },
      {
        code: loc.iataCode,
        city: toTitleCase(city),
        country: toTitleCase(country),
        // A city-level result stands for every airport in the city, so there is
        // no single airport name to put on the second line.
        name: loc.subType === 'CITY' ? undefined : toTitleCase(loc.name),
      },
    );
  };

  const selectNearby = (nearby: FlightNearbyAirport, parent: FlightLocationResult) => {
    const country = nearby.countryName || parent.countryName || '';
    // The city, not `name`. Committing `name` put "International" in the field
    // for CJB, and stored it as the recent airport's city for good.
    const city = nearby.cityName || nearby.name;
    commit(
      { destination: city, code: nearby.iataCode, country },
      {
        code: nearby.iataCode,
        city: toTitleCase(city),
        country: toTitleCase(country),
        name: airportName(nearby) || undefined,
      },
    );
  };

  const selectSuggestion = (row: SuggestionRow) =>
    commit(
      { destination: row.city, code: row.code, country: row.country },
      { code: row.code, city: row.city, country: row.country, name: row.name },
    );

  const displayName = toTitleCase(value.destination);
  const hasResults = results.length > 0;
  const searched = searchTerm.trim().length >= 2;

  return (
    <div className={`fs-field${open ? ' open' : ''}`} data-dd={dd}>
      <div
        className="fs-trigger"
        onClick={(e) => {
          e.stopPropagation();
          // Toggles, like every other field in this form.
          //
          // This used to only ever open, on the reasoning that a click while
          // open belonged to the search input — but that input lives in
          // `.fs-dropdown`, a *sibling* of this trigger, so it never receives
          // these clicks. The only thing the guard achieved was a panel with
          // no way to dismiss it from the control that opened it.
          onOpenChange(!open);
        }}
      >
        <div className="fs-head">
          <span className="fs-label">
            {icon === 'depart' ? <DepartIcon /> : <ArriveIcon />} {label}
          </span>
          <ChevronIcon />
        </div>

        {/* The chosen airport stays on screen while the panel is open — it is
            the thing the suggestions below are alternatives to. */}
        <div className="fs-value">{displayName || <span className="fs-placeholder">Select city</span>}</div>
        <div className={`fs-sub${note ? ' fs-sub-warning' : ''}`}>
          {note || toTitleCase(value.country || '')}
        </div>
      </div>

      <div className="fs-dropdown fs-airport-dd">
        {/* Sticky rather than scrolling away with the list: the panel scrolls,
            and a search box that leaves the viewport after three rows is a
            search box you have to scroll back up to correct. */}
        <div className="fs-dd-search">
          <SearchSmallIcon />
          <input
            ref={inputRef}
            id={inputId}
            type="text"
            className="fs-dd-input"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            onKeyDown={(e) => {
              // Escape closes the panel rather than only clearing the box —
              // the field is a popup, and that is what a popup does.
              if (e.key === 'Escape') {
                e.preventDefault();
                onOpenChange(false);
              }
            }}
            placeholder={label}
            autoComplete="off"
            aria-label={label}
          />
          {searchTerm && (
            <button
              type="button"
              className="fs-dd-search-clear"
              aria-label="Clear search"
              onClick={(e) => {
                e.stopPropagation();
                setSearchTerm('');
                inputRef.current?.focus();
              }}
            >
              <ClearSmallIcon />
            </button>
          )}
        </div>

        {hasResults &&
          results.map((loc, i) => (
            <div key={loc.id ?? `${loc.iataCode}-${i}`}>
              <div
                className="fs-airport-main"
                role="button"
                tabIndex={0}
                onClick={(e) => {
                  e.stopPropagation();
                  selectPrimary(loc);
                }}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    selectPrimary(loc);
                  }
                }}
              >
                <div className="fs-code">{loc.iataCode}</div>
                <div>
                  <div className="fs-ap-name fs-ap-city">{primaryDisplayName(loc)}</div>
                  <div className="fs-ap-sub">{primarySubtitle(loc)}</div>
                </div>
              </div>

              {loc.nearbyAirports && loc.nearbyAirports.length > 0 && (
                <>
                  <div className="fs-nearby-label">
                    {loc.nearbyAirports.length} nearby airport
                    {loc.nearbyAirports.length > 1 ? 's' : ''}
                    <span className="fs-nearby-radius"> · within {NEARBY_RADIUS_KM} km</span>
                  </div>
                  {loc.nearbyAirports.map((nearby, j) => (
                    <div
                      key={`${nearby.iataCode}-${j}`}
                      className="fs-airport-item"
                      role="button"
                      tabIndex={0}
                      onClick={(e) => {
                        e.stopPropagation();
                        selectNearby(nearby, loc);
                      }}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter' || e.key === ' ') {
                          e.preventDefault();
                          selectNearby(nearby, loc);
                        }
                      }}
                    >
                      <CornerIcon />
                      <div className="fs-code">{nearby.iataCode}</div>
                      <div>
                        {/* The city leads, exactly as it does on a primary row
                            above — these rows were showing `name`, so an airport
                            Amadeus calls "INTERNATIONAL" read as that and
                            nothing else. */}
                        <div className="fs-ap-name">{placeName(nearby)}</div>
                        <div className="fs-ap-sub">
                          {[airportName(nearby), nearby.distance ? `${nearby.distance.value} km from ${placeName(loc)}` : '']
                            .filter(Boolean)
                            .join(' · ')}
                        </div>
                      </div>
                    </div>
                  ))}
                </>
              )}

              {/* The nearby lookup is a second request, so the main row lands first. */}
              {loc.nearbyAirports === undefined && isLoading && (
                <div className="fs-nearby-label">Loading nearby airports…</div>
              )}
            </div>
          ))}

        {isLoading && !hasResults && <div className="fs-list-item fs-list-note">Searching…</div>}
        {!isLoading && searched && !hasResults && (
          <div className="fs-list-item fs-list-note">No airports or cities found.</div>
        )}
        {/*
          Nothing typed yet. A field that answers only "type something" wastes
          the most common case — a traveller flying from where they always fly
          from, or back along a route they just looked at. The note still shows
          when there is genuinely nothing to offer, and a `note` (origin ===
          destination) still outranks everything, because that is a problem to
          fix rather than a list to browse.
        */}
        {!searched && !hasResults && (
          <>
            {note && <div className="fs-list-item fs-list-note fs-list-note-warning">{note}</div>}

            {!note && recentRows.length > 0 && (
              <>
                <div className="fs-section-label fs-section-label-row">
                  <span>Recent searches</span>
                  <button
                    type="button"
                    className="fs-section-clear"
                    onClick={(e) => {
                      e.stopPropagation();
                      clearRecentAirports();
                      setRecents([]);
                    }}
                  >
                    Clear
                  </button>
                </div>
                {recentRows.map((row) => (
                  <SuggestionItem key={`r-${row.code}`} row={row} onSelect={selectSuggestion} />
                ))}
              </>
            )}

            {!note && curatedRows.length > 0 && (
              <>
                <div className="fs-section-label">
                  {role === 'origin' ? 'Popular departure airports' : 'Popular destinations'}
                </div>
                {curatedRows.map((row) => (
                  <SuggestionItem key={`p-${row.code}`} row={row} onSelect={selectSuggestion} />
                ))}
              </>
            )}

            {!note && recentRows.length === 0 && curatedRows.length === 0 && (
              <div className="fs-list-item fs-list-note">Type to search airports &amp; cities</div>
            )}
          </>
        )}
      </div>
    </div>
  );
}
