'use client';

import { useMemo } from 'react';
import { useSearchParams } from 'next/navigation';
import {
  CABIN_LABELS,
  decodeCabinClass,
  parseChildren,
  parseInfants,
  parseItinerary,
  tripTypeFromParams,
} from '@/services/flights/searchUrl';

interface FlightSearchSummaryBarProps {
  /** Server-resolved code -> {city, country}, so the route reads as cities on first paint. */
  initialLocationNames?: Record<string, { city: string; country: string }>;
  /** Opens the full-screen edit sheet. */
  onEdit: () => void;
}

function EditIcon() {
  return (
    <svg width={17} height={17} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
      <path d="M18.5 2.5a2.12 2.12 0 0 1 3 3L12 15l-4 1 1-4Z" />
    </svg>
  );
}

/** "Wed, 23 Sep" — short enough for a phone, unambiguous about the day. */
function shortDate(iso: string): string {
  const [y, m, d] = iso.split('-').map(Number);
  if (!y || !m || !d) return '';
  return new Date(Date.UTC(y, m - 1, d)).toLocaleDateString('en-GB', {
    weekday: 'short',
    day: 'numeric',
    month: 'short',
    timeZone: 'UTC',
  });
}

/**
 * The phone-sized replacement for the search form on the results pages.
 *
 * Below lg the compact form is not compact at all: its row wraps, its cells go
 * full width, and the result is a stacked form roughly a viewport tall sitting
 * in a `position: fixed` bar — which is what was covering the results. A phone
 * has no room to keep six editable fields on screen while someone reads a list
 * of flights, so it shows what was searched for and gets out of the way, with
 * one control to change it.
 *
 * Reads the search from the URL rather than form state: the URL is what the
 * results were fetched from, so this can never describe a search the list below
 * it is not showing.
 */
export default function FlightSearchSummaryBar({
  initialLocationNames,
  onEdit,
}: FlightSearchSummaryBarProps) {
  const searchParams = useSearchParams();

  const summary = useMemo(() => {
    const segments = parseItinerary(searchParams.get('itinerary'));
    if (segments.length === 0) return null;

    const tripType = tripTypeFromParams(searchParams);
    const first = segments[0];
    const last = segments[segments.length - 1];
    const cityFor = (code: string) => initialLocationNames?.[code]?.city || code;

    // Multi-city is the first origin to the final destination with a leg count:
    // spelling out four legs is unreadable at this width, and the form behind
    // Edit is where the full route belongs.
    const route =
      tripType === 'multicity'
        ? `${cityFor(first.from)} → ${cityFor(last.to)} · ${segments.length} legs`
        : `${cityFor(first.from)} → ${cityFor(first.to)}`;

    const adults = Math.max(1, Number(searchParams.get('adults')) || 1);
    const travellers = adults + parseChildren(searchParams) + parseInfants(searchParams.get('infants'));
    const cabin = CABIN_LABELS[decodeCabinClass(searchParams.get('cabinClass'))];

    const dates =
      tripType === 'roundtrip' && segments.length > 1
        ? `${shortDate(first.date)} – ${shortDate(last.date)}`
        : shortDate(first.date);

    return {
      route,
      meta: [dates, `${travellers} traveller${travellers === 1 ? '' : 's'}`, cabin]
        .filter(Boolean)
        .join(' · '),
    };
  }, [searchParams, initialLocationNames]);

  // Nothing searched for yet — there is no journey to summarise.
  if (!summary) return null;

  return (
    <div className="flight-summary-bar">
      <div className="flight-summary-bar__text">
        <div className="flight-summary-bar__route">{summary.route}</div>
        <div className="flight-summary-bar__meta">{summary.meta}</div>
      </div>
      <button
        type="button"
        className="flight-summary-bar__edit"
        onClick={onEdit}
        aria-label="Edit search"
      >
        <EditIcon />
        <span>Edit</span>
      </button>
    </div>
  );
}
