'use client';

import { useEffect, useRef } from 'react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import {
  parseItinerary,
  parseChildren,
  parseInfants,
  decodeCabinClass,
} from '@/services/flights/searchUrl';
import {
  buildDateStrip,
  dateStripAnchor,
  dateStripHref,
  type DateStripCell,
} from '@/services/flights/dateStrip';
import { parseBookingFor } from '@/services/employee-requests/booking-for';
import { useDateStripPrices } from './useDateStripPrices';
import { formatFlightMoney } from '@/services/flights/formatPrice';
import { Skeleton } from '@/components/ui/Skeleton';
import { parseDateOnlyAsLocal } from '@/utils/date';
import './flight-date-strip.css';

/**
 * "Thu, Sep 17" — the exact options the SRP header below uses, so the strip and
 * the search summary it sits above never render the same date two ways. en-GB
 * would abbreviate September to "Sept", one character wider than every other
 * month, which shows up as a jitter across a row of seven equal cells.
 */
const LONG = new Intl.DateTimeFormat('en-US', { weekday: 'short', day: '2-digit', month: 'short' });
/** "Sep 17" — the compact half of a round-trip pair, where the weekday cannot fit twice. */
const SHORT = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric' });

function format(iso: string, fmt: Intl.DateTimeFormat): string {
  const date = parseDateOnlyAsLocal(iso);
  return date ? fmt.format(date) : iso;
}

/** What the cell reads: one date, or the pair a round trip actually moves. */
function cellLabel(cell: DateStripCell): string {
  return cell.returnDate
    ? `${format(cell.departDate, SHORT)} - ${format(cell.returnDate, SHORT)}`
    : format(cell.departDate, LONG);
}

interface FlightDateStripProps {
  /**
   * Multi-city has no strip at all — see dateStrip.ts. The prop exists so a
   * caller cannot accidentally render one by passing the wrong params.
   */
  tripType: 'oneway' | 'roundtrip';
}

/**
 * Seven nearby dates, each a link to the same search on a different day.
 *
 * Reads the URL rather than taking a dozen props: the URL is already the single
 * source of truth for a flight search — both SRP clients derive their own state
 * from it, and the search re-runs off the `departDate` they read there — so a
 * cell only has to change the address for everything downstream to follow.
 *
 * Real `<a>`s, not buttons: a traveller comparing two dates can open one in a
 * second tab, and `scroll={false}` keeps the results where they were instead of
 * jumping to the top of a page whose layout has not changed.
 */
export default function FlightDateStrip({ tripType }: FlightDateStripProps) {
  const searchParams = useSearchParams();
  const scrollerRef = useRef<HTMLDivElement>(null);
  const selectedRef = useRef<HTMLAnchorElement>(null);

  const segments = parseItinerary(searchParams.get('itinerary'));
  const from = segments[0]?.from ?? '';
  const to = segments[0]?.to ?? '';
  const departDate = segments[0]?.date ?? '';
  const returnDate = tripType === 'roundtrip' ? segments[1]?.date ?? '' : '';

  const cells =
    from && to && departDate && (tripType === 'oneway' || returnDate)
      ? buildDateStrip({ departDate, returnDate: returnDate || null })
      : [];

  // The strip scrolls horizontally on a narrow viewport, where the selected
  // date can start off-screen. Centring it on mount — and again whenever the
  // search moves — is what keeps "where am I" answerable without a swipe.
  useEffect(() => {
    const scroller = scrollerRef.current;
    const selected = selectedRef.current;
    if (!scroller || !selected) return;
    if (scroller.scrollWidth <= scroller.clientWidth) return;
    scroller.scrollLeft = selected.offsetLeft - (scroller.clientWidth - selected.offsetWidth) / 2;
  }, [departDate, returnDate]);

  const hrefInput = {
    from,
    to,
    adults: Number(searchParams.get('adults') ?? 1) || 1,
    children: parseChildren(searchParams),
    infants: parseInfants(searchParams.get('infants')),
    cabinClass: decodeCabinClass(searchParams.get('cabinClass')),
    directOnly: searchParams.get('directOnly') === 'true',
    // CORP-ONLY (LEIS-934): a cell rebuilds the whole search URL, so who the
    // trip is for has to ride along or a cheaper date resets it to you.
    bookingFor: parseBookingFor(searchParams),
  };

  /*
   * Built above the early return because hooks cannot be called after one.
   * Null whenever there is nothing to price — the hook reads that as "stay
   * idle" rather than firing a request the strip has no cells to spend it on.
   *
   * Anchored on the strip's middle cell, never on the searched date. See
   * dateStripAnchor for why those differ and when.
   */
  const anchorDate = dateStripAnchor(cells);
  const priceInput =
    anchorDate && from && to && departDate
      ? {
          tripType,
          from,
          to,
          departDate,
          returnDate: returnDate || null,
          anchorDate,
          adults: hrefInput.adults,
          children: hrefInput.children,
          infants: hrefInput.infants,
          cabin: hrefInput.cabinClass,
          directOnly: hrefInput.directOnly,
        }
      : null;

  const { status: priceStatus, priceByDate, symbol } = useDateStripPrices(priceInput);

  if (cells.length === 0) return null;

  return (
    <nav className="flight-date-strip" aria-label="Nearby departure dates">
      {/*
        Said once for the whole strip. The skeleton boxes are aria-hidden by
        default, so without this a screen-reader user gets no signal at all
        that seven prices are on their way — and with a per-cell live region
        they would get seven.
      */}
      <span className="visually-hidden" role="status" aria-live="polite">
        {priceStatus === 'loading'
          ? 'Loading prices for nearby dates'
          : priceStatus === 'ready' && priceByDate.size > 0
            ? 'Prices for nearby dates updated'
            : ''}
      </span>
      <div className="flight-date-strip__scroller" ref={scrollerRef}>
        {cells.map((cell) => (
          <Link
            key={cell.departDate}
            ref={cell.isSelected ? selectedRef : undefined}
            href={dateStripHref(cell, hrefInput)}
            scroll={false}
            className={`flight-date-strip__cell${cell.isSelected ? ' is-selected' : ''}`}
            // aria-current marks the date being shown, so a screen reader does
            // not have to infer it from the styling.
            aria-current={cell.isSelected ? 'date' : undefined}
          >
            <span className="flight-date-strip__date">{cellLabel(cell)}</span>
            {/*
              One slot, three states, one height — the skeleton, the price and
              the "View" link all occupy the same box so nothing on the page
              moves when prices land 10 seconds after the list.

              "View" is not only the error state: it is what a cell shows for a
              date the airline never priced, and what every cell showed before
              this feature existed. A fare we do not have is not a zero.
            */}
            <span className="flight-date-strip__slot">
              {priceStatus === 'loading' ? (
                <Skeleton h={11} w="70%" rounded={3} />
              ) : priceByDate.has(cell.departDate) ? (
                <span className="flight-date-strip__price">
                  {formatFlightMoney(symbol, priceByDate.get(cell.departDate)!)}
                </span>
              ) : (
                <span className="flight-date-strip__action">View</span>
              )}
            </span>
          </Link>
        ))}
      </div>
    </nav>
  );
}
