'use client';

import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { resetFilters, setActiveSort, setFilters } from '@/store/slices/flightSearch.slice';
import type { SortKey } from '@/services/flights/filterSort';
import type { FlightData } from './types';
import FlightFilterSidebar from './FlightFilterSidebar';
import type { SmartFilterRouteContext } from '@/services/flights/smartFilters/types';
import './flight-mobile-filters.css';

/** Must match the transition duration in flight-mobile-filters.css. */
const SHEET_ANIMATION_MS = 260;

const SORT_OPTIONS: { key: SortKey; label: string; hint: string }[] = [
  { key: 'best', label: 'Best', hint: 'Recommended' },
  { key: 'cheapest', label: 'Price', hint: 'Cheapest first' },
  { key: 'fastest', label: 'Duration', hint: 'Fastest first' },
  { key: 'earliest', label: 'Departure time', hint: 'Earliest first' },
  { key: 'earliest-arrival', label: 'Arrival time', hint: 'Earliest first' },
];

function SlidersIcon() {
  return (
    <svg width={17} height={17} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" aria-hidden="true">
      <path d="M4 21v-7M4 10V3M12 21v-9M12 8V3M20 21v-5M20 12V3M1 14h6M9 8h6M17 16h6" />
    </svg>
  );
}

interface FlightMobileFilterBarProps {
  /** The offers the current view renders, for the sidebar's facets. */
  offers: FlightData[];
  /** How many results the active filters produce, for the drawer header. */
  resultCount: number;
  totalCount: number;
  /** Route/date context Smart Filters needs alongside `offers` — omitted only
   *  by call sites that haven't been wired up to it yet, which simply don't
   *  get the card. */
  searchContext?: SmartFilterRouteContext;
}

/**
 * Filters and sort on a phone.
 *
 * On desktop both live in a left column. Below lg that column is ordered after
 * the entire flight list, so the only way to reach a filter was to scroll past
 * every result — which is indistinguishable from them not being there.
 *
 * This is the pattern every mobile travel site converged on for the same
 * reason: a fixed bar at the thumb end of the screen, with the refinements
 * people actually reach for as one-tap chips and everything else behind a
 * drawer.
 */
export default function FlightMobileFilterBar({
  offers,
  resultCount,
  totalCount,
  searchContext,
}: FlightMobileFilterBarProps) {
  const dispatch = useAppDispatch();
  const filters = useAppSelector((state) => state.flightSearch.filters);
  const activeSort = useAppSelector((state) => state.flightSearch.activeSort);
  const [open, setOpen] = useState(false);
  const barRef = useRef<HTMLDivElement>(null);

  /**
   * Publish this bar's height, and flag the page as having one.
   *
   * The bar is fixed, so it costs no layout space and the page simply ends
   * underneath it — which put the last line of the footer out of reach. A
   * padding on the results section could not fix that: the footer comes after
   * it. The class is on `body` so the rule can reach the footer, and the
   * height is measured rather than hardcoded because the chip row can wrap to
   * a second line on a narrow phone.
   *
   * Both are cleaned up on unmount, so a page without results — where this
   * does not render — keeps its normal bottom.
   */
  useEffect(() => {
    const root = document.documentElement;
    document.body.classList.add('has-flight-filterbar');

    const measure = () => {
      const h = barRef.current?.getBoundingClientRect().height ?? 0;
      if (h > 0) root.style.setProperty('--flight-filterbar-h', `${Math.round(h)}px`);
    };
    measure();

    const observer = new ResizeObserver(measure);
    if (barRef.current) observer.observe(barRef.current);
    window.addEventListener('resize', measure);

    return () => {
      observer.disconnect();
      window.removeEventListener('resize', measure);
      document.body.classList.remove('has-flight-filterbar');
      root.style.removeProperty('--flight-filterbar-h');
    };
  }, []);

  /**
   * How many refinements are on, for the badge.
   *
   * Counted per *control*, not per selected value: someone who ticked three
   * airlines has used one filter, and a badge reading "3" would suggest three
   * separate things to go and undo.
   */
  const activeCount = useMemo(() => {
    let n = 0;
    if (filters.stops.length) n += 1;
    if (filters.airlines.length) n += 1;
    if (filters.maxPrice != null) n += 1;
    if (filters.maxDurationMinutes != null) n += 1;
    if (filters.maxLayoverMinutes != null) n += 1;
    if (filters.departureHourRange[0] !== 0 || filters.departureHourRange[1] !== 24) n += 1;
    if (filters.arrivalHourRange[0] !== 0 || filters.arrivalHourRange[1] !== 24) n += 1;
    if (filters.refundableOnly) n += 1;
    if (filters.checkedBagsOnly) n += 1;
    return n;
  }, [filters]);

  /**
   * The chips, built from what this search actually returned.
   *
   * Airlines come from the results rather than a fixed list, so a chip never
   * offers a carrier that would filter the page to nothing. Two of them: enough
   * to cover the common "just show me IndiGo" without the row becoming a
   * second filter panel.
   */
  const airlineChips = useMemo(() => {
    const seen = new Map<string, number>();
    for (const offer of offers) {
      const name = offer.outbound?.airline?.name;
      if (name) seen.set(name, (seen.get(name) ?? 0) + 1);
    }
    return [...seen.entries()]
      .sort((a, b) => b[1] - a[1])
      .slice(0, 2)
      .map(([name]) => name);
  }, [offers]);

  const toggleStop = (value: '0' | '1' | '2+') => {
    const next = filters.stops.includes(value)
      ? filters.stops.filter((s) => s !== value)
      : [...filters.stops, value];
    dispatch(setFilters({ stops: next }));
  };

  const toggleAirline = (name: string) => {
    const next = filters.airlines.includes(name)
      ? filters.airlines.filter((a) => a !== name)
      : [...filters.airlines, name];
    dispatch(setFilters({ airlines: next }));
  };

  return (
    <>
      <div className="flight-mobile-filterbar" ref={barRef}>
        {/* Scrolls horizontally rather than wrapping: a bar that grows to two
            rows on a narrow phone eats the results it is meant to refine, and
            the chip set is genuinely open-ended. */}
        <div className="flight-mobile-filterbar__chips">
          <button
            type="button"
            className={`fmf-chip${filters.stops.includes('0') ? ' is-on' : ''}`}
            onClick={() => toggleStop('0')}
            aria-pressed={filters.stops.includes('0')}
          >
            Non-stop
          </button>
          <button
            type="button"
            className={`fmf-chip${filters.refundableOnly ? ' is-on' : ''}`}
            onClick={() => dispatch(setFilters({ refundableOnly: !filters.refundableOnly }))}
            aria-pressed={filters.refundableOnly}
          >
            Refundable
          </button>
          <button
            type="button"
            className={`fmf-chip${filters.checkedBagsOnly ? ' is-on' : ''}`}
            onClick={() => dispatch(setFilters({ checkedBagsOnly: !filters.checkedBagsOnly }))}
            aria-pressed={filters.checkedBagsOnly}
          >
            Checked bag
          </button>
          {airlineChips.map((name) => (
            <button
              key={name}
              type="button"
              className={`fmf-chip${filters.airlines.includes(name) ? ' is-on' : ''}`}
              onClick={() => toggleAirline(name)}
              aria-pressed={filters.airlines.includes(name)}
            >
              {name}
            </button>
          ))}
        </div>

        <button
          type="button"
          className="flight-mobile-filterbar__open"
          onClick={() => setOpen(true)}
        >
          <SlidersIcon />
          <span>Sort &amp; Filters</span>
          {activeCount > 0 ? <span className="fmf-badge">{activeCount}</span> : null}
        </button>
      </div>

      {open ? (
        <FlightFilterSheet
          offers={offers}
          searchContext={searchContext}
          resultCount={resultCount}
          totalCount={totalCount}
          activeSort={activeSort}
          activeCount={activeCount}
          onSort={(key) => dispatch(setActiveSort(key))}
          onClearAll={() => dispatch(resetFilters())}
          onClose={() => setOpen(false)}
        />
      ) : null}
    </>
  );
}

/**
 * The drawer, up from the bottom.
 *
 * Filters apply as they are ticked, exactly as the desktop sidebar does, so
 * Apply confirms and closes rather than committing — which is why the header
 * counts results live: the number moving is the feedback that a tick landed.
 */
function FlightFilterSheet({
  offers,
  searchContext,
  resultCount,
  totalCount,
  activeSort,
  activeCount,
  onSort,
  onClearAll,
  onClose,
}: {
  offers: FlightData[];
  searchContext?: SmartFilterRouteContext;
  resultCount: number;
  totalCount: number;
  activeSort: SortKey;
  activeCount: number;
  onSort: (key: SortKey) => void;
  onClearAll: () => void;
  onClose: () => void;
}) {
  const [tab, setTab] = useState<'filters' | 'sort'>('filters');
  const [entered, setEntered] = useState(false);
  const [leaving, setLeaving] = useState(false);
  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    const frame = requestAnimationFrame(() => setEntered(true));
    return () => cancelAnimationFrame(frame);
  }, []);

  useEffect(() => () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
  }, []);

  const startClose = useCallback(() => {
    if (closeTimer.current) return;
    setLeaving(true);
    closeTimer.current = setTimeout(onClose, SHEET_ANIMATION_MS);
  }, [onClose]);

  useEffect(() => {
    const previous = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = previous;
    };
  }, []);

  useEffect(() => {
    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') startClose();
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [startClose]);

  const openClass = entered && !leaving ? ' is-open' : '';

  return (
    <>
      <div className={`fmf-backdrop${openClass}`} onClick={startClose} aria-hidden="true" />
      <div className={`fmf-sheet${openClass}`} role="dialog" aria-modal="true" aria-label="Sort and filters">
        <div className="fmf-sheet__head">
          <div>
            <div className="fmf-sheet__title">Sort &amp; Filters</div>
            <div className="fmf-sheet__count">
              {resultCount} of {totalCount} results
            </div>
          </div>
          <button type="button" className="fmf-sheet__close" onClick={startClose} aria-label="Close sort and filters">
            <svg width={20} height={20} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" aria-hidden="true">
              <path d="M18 6 6 18" />
              <path d="m6 6 12 12" />
            </svg>
          </button>
        </div>

        <div className="fmf-sheet__tabs" role="tablist">
          <button
            type="button"
            role="tab"
            aria-selected={tab === 'filters'}
            className={`fmf-tab${tab === 'filters' ? ' is-active' : ''}`}
            onClick={() => setTab('filters')}
          >
            Filters{activeCount > 0 ? ` (${activeCount})` : ''}
          </button>
          <button
            type="button"
            role="tab"
            aria-selected={tab === 'sort'}
            className={`fmf-tab${tab === 'sort' ? ' is-active' : ''}`}
            onClick={() => setTab('sort')}
          >
            Sort by
          </button>
        </div>

        <div className="fmf-sheet__body">
          {tab === 'filters' ? (
            /* The desktop sidebar, unchanged. Its controls already dispatch
               to the same store, so there is no second implementation of a
               filter to keep in step with this one — Smart Filters and
               Applied Filters are FlightFilterSidebar's own first sections,
               not mounted separately here. */
            <FlightFilterSidebar
              offers={offers}
              onClearFilters={onClearAll}
              variant="sheet"
              smartFiltersContext={searchContext}
            />
          ) : (
            <ul className="fmf-sort-list">
              {SORT_OPTIONS.map((option) => (
                <li key={option.key}>
                  <button
                    type="button"
                    className={`fmf-sort${activeSort === option.key ? ' is-active' : ''}`}
                    onClick={() => onSort(option.key)}
                    aria-pressed={activeSort === option.key}
                  >
                    <span className="fmf-sort__label">{option.label}</span>
                    <span className="fmf-sort__hint">{option.hint}</span>
                  </button>
                </li>
              ))}
            </ul>
          )}
        </div>

        <div className="fmf-sheet__foot">
          <button
            type="button"
            className="fmf-clear"
            onClick={onClearAll}
            disabled={activeCount === 0}
          >
            Clear all
          </button>
          <button type="button" className="fmf-apply" onClick={startClose}>
            Show {resultCount} {resultCount === 1 ? 'flight' : 'flights'}
          </button>
        </div>
      </div>
    </>
  );
}

