'use client';

import Link from 'next/link';
import { useSyncExternalStore, type ReactNode } from 'react';

import type { FlightError, FlightErrorCode } from '@/services/flights/errors';
import { safeBackHref } from '@/services/flights/returnToSearch';

/**
 * Every illustration shares this canvas, ground shadow and palette so the three
 * variants read as one family — and as siblings of FlightsEmptyState /
 * FlightsErrorState, which travellers have already seen on the results page.
 *
 * Colours come from --color-first / --color-second only. Both are declared with
 * light-dark(), so a hardcoded hex here would survive the light theme and break
 * the dark one.
 */
const CANVAS = { width: 220, height: 150, viewBox: '0 0 220 150' } as const;

/**
 * Connectivity, read straight from the browser rather than mirrored into state.
 *
 * `navigator.onLine` is an external value that changes without React's
 * involvement, which is exactly what useSyncExternalStore is for — copying it
 * into state inside an effect would re-render on mount for no reason.
 *
 * The server snapshot is `true`: a disabled retry button on a working
 * connection is a worse failure than a retry that turns out to fail, and
 * `onLine` is false-negative-prone in any case.
 */
function subscribeToConnectivity(onChange: () => void) {
  window.addEventListener('online', onChange);
  window.addEventListener('offline', onChange);
  return () => {
    window.removeEventListener('online', onChange);
    window.removeEventListener('offline', onChange);
  };
}

function Ground() {
  return <ellipse cx={110} cy={128} rx={70} ry={8} fill="var(--color-first, #2f6271)" opacity={0.08} />;
}

/** Price hold ended: the sand has run out, and the flight has left without them. */
function HoldExpiredIllustration() {
  return (
    <svg {...CANVAS} fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <Ground />

      {/* Hourglass centred on x=110 so it sits over the shared ground ellipse. */}
      <path d="M93 42h34M93 114h34" stroke="var(--color-first, #2f6271)" strokeWidth={3} strokeLinecap="round" />
      <path
        d="M97 42c0 18 13 24 13 36s-13 18-13 36M123 42c0 18-13 24-13 36s13 18 13 36"
        stroke="var(--color-first, #2f6271)"
        strokeWidth={2.5}
        strokeLinejoin="round"
      />
      {/* Upper bulb empty, lower bulb full — the hold is spent, not running. */}
      <path d="M101 106c0-9 6-14 9-14s9 5 9 14Z" fill="var(--color-second, #f45d6b)" opacity={0.85} />
      <circle cx={110} cy={86} r={2} fill="var(--color-second, #f45d6b)" opacity={0.55} />

      {/* The flight, already gone — trail leaving the frame past the hourglass. */}
      <path
        d="M136 60c12-6 24-11 38-15"
        stroke="var(--color-first, #2f6271)"
        strokeOpacity={0.3}
        strokeWidth={2}
        strokeDasharray="1 8"
        strokeLinecap="round"
      />
      <g transform="translate(172 26) rotate(-18)">
        <path d="M0 11 24 0 5 22 2 14Z" fill="var(--color-first, #2f6271)" opacity={0.6} />
        <path d="M0 11 11 13 2 14Z" fill="var(--color-second, #f45d6b)" opacity={0.6} />
      </g>
    </svg>
  );
}

/** Couldn't reach the flight service — the journey stops short of the gate. */
/* corp: the user-facing copy below says "request", not "booking", and
 * "nothing has been requested or charged" rather than "nothing has been
 * charged". An employee on this flow never books and never pays; telling
 * them a booking failed describes a step that does not exist for them. */
function ConnectionLostIllustration() {
  return (
    <svg {...CANVAS} fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <Ground />

      {/* Path runs, then simply stops — nothing is wrong with the fare, we just
          couldn't get there. Deliberately the same visual language as
          FlightsErrorState: same class of failure, same idea. */}
      <path
        d="M36 104C58 82 82 68 104 58"
        stroke="var(--color-first, #2f6271)"
        strokeOpacity={0.35}
        strokeWidth={2}
        strokeDasharray="1 8"
        strokeLinecap="round"
      />
      <circle cx={36} cy={104} r={4} fill="var(--color-first, #2f6271)" opacity={0.45} />

      <g transform="translate(106 40)">
        <path d="M0 14 30 0 6 28 3 18Z" fill="var(--color-first, #2f6271)" opacity={0.6} />
        <path d="M0 14 14 16 3 18Z" fill="var(--color-second, #f45d6b)" opacity={0.6} />
      </g>

      {/* Destination it never reached. */}
      <path d="M168 68v30" stroke="var(--color-first, #2f6271)" strokeWidth={2} strokeDasharray="1 7" opacity={0.3} strokeLinecap="round" />
      <circle cx={168} cy={104} r={4} fill="var(--color-first, #2f6271)" opacity={0.2} />

      <circle cx={168} cy={54} r={13} fill="var(--bgColor-white, #fff)" stroke="var(--color-second, #f45d6b)" strokeWidth={2} />
      <path d="M168 48v7M168 60h.01" stroke="var(--color-second, #f45d6b)" strokeWidth={2} strokeLinecap="round" />
    </svg>
  );
}

/** The fare itself is gone — a boarding pass that can no longer be used. */
function FareUnavailableIllustration() {
  return (
    <svg {...CANVAS} fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <Ground />

      <rect x={56} y={44} width={108} height={64} rx={8} stroke="var(--color-first, #2f6271)" strokeWidth={2.5} opacity={0.7} />
      {/* tear line down the middle of the pass */}
      <path d="M124 44v64" stroke="var(--color-first, #2f6271)" strokeWidth={2} strokeDasharray="4 5" opacity={0.45} />
      <path d="M68 62h44M68 76h30" stroke="var(--color-first, #2f6271)" strokeWidth={2.5} strokeLinecap="round" opacity={0.35} />

      <g transform="translate(132 62)">
        <path d="M0 10 20 0 4 20 2 13Z" fill="var(--color-first, #2f6271)" opacity={0.5} />
      </g>

      <circle cx={150} cy={104} r={14} fill="var(--bgColor-white, #fff)" stroke="var(--color-second, #f45d6b)" strokeWidth={2} />
      <path d="M145 99l10 10M155 99l-10 10" stroke="var(--color-second, #f45d6b)" strokeWidth={2} strokeLinecap="round" />
    </svg>
  );
}

/** The fare still exists — its price moved while they were deciding. */
function PriceChangedIllustration() {
  return (
    <svg {...CANVAS} fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <Ground />

      {/* A fare tag, intact — nothing here is broken or gone. */}
      <path
        d="M96 46h38a8 8 0 0 1 8 8v38a8 8 0 0 1-8 8H96L62 76Z"
        stroke="var(--color-first, #2f6271)"
        strokeWidth={2.5}
        strokeLinejoin="round"
        opacity={0.75}
      />
      <circle cx={104} cy={76} r={5} stroke="var(--color-first, #2f6271)" strokeWidth={2.5} opacity={0.55} />

      {/* Arrows up and down: the number changed, in whichever direction. */}
      <path d="M160 92V56m0 0-8 9m8-9 8 9" stroke="var(--color-second, #f45d6b)" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round" />
      <path d="M182 56v36m0 0 8-9m-8 9-8-9" stroke="var(--color-first, #2f6271)" strokeWidth={2.5} strokeLinecap="round" strokeLinejoin="round" opacity={0.5} />
    </svg>
  );
}

/** Booking is switched off on our side — nothing for them to retry into. */
function ServicePausedIllustration() {
  return (
    <svg {...CANVAS} fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
      <Ground />

      {/* A plane parked on the ground rather than in flight. */}
      <g transform="translate(66 52)">
        <path d="M0 22 44 0 12 40 8 28Z" fill="var(--color-first, #2f6271)" opacity={0.45} />
        <path d="M0 22 20 25 8 28Z" fill="var(--color-second, #f45d6b)" opacity={0.45} />
      </g>

      {/* Paused, not broken: two bars, the universal "we'll resume" mark. */}
      <circle cx={152} cy={72} r={22} fill="var(--bgColor-white, #fff)" stroke="var(--color-first, #2f6271)" strokeWidth={2.5} opacity={0.9} />
      <path d="M146 63v18M158 63v18" stroke="var(--color-first, #2f6271)" strokeWidth={3} strokeLinecap="round" opacity={0.8} />
    </svg>
  );
}

interface Variant {
  illustration: ReactNode;
  title: string;
  /**
   * The body copy for this screen.
   *
   * Preferred over `error.message`, which is one line written to work in a
   * toast or beside a field. Here there is a title above it and room below, so
   * the same sentence would either repeat the heading or be thinner than the
   * space deserves.
   */
  fallbackMessage: string;
  /**
   * Show `error.message` instead. Only for codes whose text is authored by the
   * service for this specific traveller — per the API contract that is
   * VALIDATION_ERROR alone, where the message names the field that was wrong
   * and generic copy would hide it.
   */
  preferErrorMessage?: boolean;
  /**
   * One extra line, only where it changes what the traveller does next. Most
   * variants have none — a reassuring sentence that says nothing is noise on a
   * screen someone is already unhappy to be reading.
   */
  hint?: string;
  /** Wording for the retry button, when the error is retryable at all. */
  retryLabel?: string;
  /** Wording for the link back to search. */
  backLabel?: string;
  /**
   * Whether searching again is a sensible thing to offer. It is not when the
   * whole flight product is switched off — that link leads to a page that will
   * fail the same way.
   */
  offerSearch?: boolean;
}

/**
 * One screen, several faces. This is shown for every review-load failure, and
 * the right words differ sharply between them: telling someone their fare
 * vanished when the real problem is our upstream being briefly down sends them
 * to redo a search they never needed to redo.
 *
 * Every code in the taxonomy is named here on purpose. A `default` that swept
 * the remainder into "this fare is no longer available" is precisely the
 * mistake above — it claimed a fare had gone for a price change, for a
 * malformed request of ours, and for flights being switched off entirely, none
 * of which are true and two of which sent the traveller somewhere useless.
 */
function variantFor(code: FlightErrorCode | undefined): Variant {
  switch (code) {
    case 'FLIGHT_SESSION_EXPIRED':
      return {
        illustration: <HoldExpiredIllustration />,
        title: 'Your price hold has ended',
        fallbackMessage:
          'We held this fare for 15 minutes and that time has now passed. Search again for the latest prices.',
        backLabel: 'Search again',
        offerSearch: true,
      };

    // The fare itself is gone. Retrying the same offer cannot bring it back.
    case 'FLIGHT_OFFER_INVALID':
    case 'FLIGHT_INVALID_DATA':
      return {
        illustration: <FareUnavailableIllustration />,
        title: 'This fare is no longer available',
        fallbackMessage:
          'Someone booked the last seat at this price, or the airline withdrew it. Search again to find the latest options.',
        backLabel: 'Search again',
        offerSearch: true,
      };

    // A flight was withdrawn between search and pricing. Reads as the fare
    // being gone, but the message is the point: on a multi-city the service
    // has worked out *which* leg died, and that sentence names it. Generic
    // copy here would throw away the only thing that makes this recoverable
    // without rebuilding the whole trip — hence preferErrorMessage.
    case 'FLIGHT_OFFER_UNAVAILABLE':
      return {
        illustration: <FareUnavailableIllustration />,
        title: 'A selected flight is no longer available',
        preferErrorMessage: true,
        fallbackMessage:
          'The airline withdrew this flight after you chose it. Search again to pick a replacement.',
        hint: 'Nothing has been requested or charged.',
        backLabel: 'Back to flight search',
        offerSearch: true,
      };

    // The flight is fine; its price moved while they were deciding. Worth its
    // own face, because "the price changed" and "the fare is gone" ask for very
    // different amounts of patience from the traveller.
    //
    // No retry button: the taxonomy marks this non-retryable because repeating
    // the identical request returns the identical discrepancy. A fresh search is
    // the only thing that actually shows a current price, so that is what is
    // offered — promising "see the new price" here would be a button that
    // reproduces the error.
    case 'FLIGHT_PRICE_DISCREPANCY':
      return {
        illustration: <PriceChangedIllustration />,
        title: 'The price has changed',
        fallbackMessage:
          'Airlines can reprice a fare while a request is being put together, so the price we held is no longer current. Search again for live prices.',
        hint: 'Nothing has been requested or charged.',
        backLabel: 'Search again',
        offerSearch: true,
      };

    // Flights are switched off on our side. "Search again" would lead straight
    // into the same wall, so it is deliberately not offered.
    case 'FLIGHTS_DISABLED':
      return {
        illustration: <ServicePausedIllustration />,
        title: 'Flight requests are paused',
        fallbackMessage:
          'Flight requests are temporarily unavailable while we carry out maintenance. Nothing has been requested or charged.',
        hint: 'Hotels and cruises are unaffected.',
        offerSearch: false,
      };

    // Their connection, not ours. The retry button waits for the browser to
    // come back online rather than firing into a dead network.
    case 'NETWORK_ERROR':
      return {
        illustration: <ConnectionLostIllustration />,
        title: 'You appear to be offline',
        fallbackMessage:
          'We could not reach Leisure.com. Check your connection and try again — your request has not been lost.',
        retryLabel: 'Try again',
        backLabel: 'Back to flight search',
        offerSearch: true,
      };

    // We sent something the service would not accept. Repeating it identically
    // would fail identically, so retry is not the way out — a fresh search is.
    case 'VALIDATION_ERROR':
    case 'FLIGHT_FORMAT':
      return {
        illustration: <ConnectionLostIllustration />,
        title: "We couldn't process this request",
        fallbackMessage:
          'Something in this request was not right on our side. Starting a new search should clear it.',
        // VALIDATION_ERROR carries copy the service wrote about this exact
        // request, naming the field at fault. Generic text would lose that.
        preferErrorMessage: true,
        backLabel: 'Start a new search',
        offerSearch: true,
      };

    case 'FLIGHT_AUTH':
    case 'FLIGHT_UPSTREAM':
    case 'UNKNOWN':
    default:
      return {
        illustration: <ConnectionLostIllustration />,
        title: "We couldn't load your request",
        fallbackMessage:
          'Something went wrong reaching our flight partner. Please try again in a moment.',
        hint: 'Nothing has been requested or charged.',
        retryLabel: 'Try again',
        backLabel: 'Back to flight search',
        offerSearch: true,
      };
  }
}

interface FlightReviewUnavailableProps {
  /**
   * The structured failure. `message` is written for a traveller; upstream
   * diagnostic text stays in `detail` and is logged, never rendered.
   */
  error?: FlightError | null;
  /**
   * Where "search again" goes — the search this review started from, already
   * validated by the page. Falls back to the plain flight search page.
   */
  backHref?: string;
  /**
   * Overrides the default retry (reloading the page). Only ever offered for
   * errors the taxonomy marks retryable: inviting someone to retry an expired
   * hold would just fail again, more slowly.
   */
  onRetry?: () => void;
  /**
   * The review session id. Shown as a quotable reference so a traveller who
   * contacts support can say which booking attempt failed, instead of
   * describing it.
   */
  reference?: string;
}

export default function FlightReviewUnavailable({
  error,
  backHref,
  onRetry,
  reference,
}: FlightReviewUnavailableProps) {
  const variant = variantFor(error?.code);
  const message = variant.preferErrorMessage
    ? error?.message || variant.fallbackMessage
    : variant.fallbackMessage;
  const searchHref = safeBackHref(backHref);
  const canRetry = error?.retryable ?? false;
  const isOffline = error?.code === 'NETWORK_ERROR';

  // Retrying into a dead network only reproduces the error, so on the offline
  // variant the button waits for the browser to report a connection again.
  const online = useSyncExternalStore(
    subscribeToConnectivity,
    () => navigator.onLine,
    () => true,
  );
  const retryDisabled = isOffline && !online;

  function handleRetry() {
    if (onRetry) return onRetry();
    // Re-runs the loader's fetch from scratch. The loader caches its request on
    // a ref for the life of a mount, so a full reload is the honest way to ask
    // for a genuinely fresh attempt.
    window.location.reload();
  }

  // Search is the primary action whenever retry is not on offer — but only
  // when searching is actually a way out. With flights switched off it is not,
  // and the screen is honest about having nothing to click.
  const searchIsPrimary = !canRetry && variant.offerSearch !== false;

  return (
    <section className="py-md-5 py-3 booking-detail-listing-section travelContent">
      <div className="container webNewContent">
        <div className="row justify-content-center">
          {/* Narrower than the page's content column on purpose: this card holds
              one short message, and stretching it to the full width left the
              text a small island in a large empty box. */}
          <div className="col-xl-6 col-lg-7 col-md-9 col-12">
            <div
              className="flight-review-unavailable bgColor-white rounded-3 text-center px-3 px-md-4"
              style={{
                // Neutral grey rather than a fixed light hex: this card is white
                // in the light theme and near-black in the dark one.
                border: '1px solid rgba(128,128,128,0.25)',
                paddingTop: '2.75rem',
                paddingBottom: '2.5rem',
              }}
            >
              {variant.illustration}

              <h1 className="text-xxl fw-600 color-text-dark mb-2 mt-3">{variant.title}</h1>
              <p
                className="text-md color-text-gray mb-0 mx-auto"
                style={{ maxWidth: 420, lineHeight: 1.6 }}
              >
                {message}
              </p>
              {variant.hint ? (
                <p className="text-sm color-text-gray mb-0 mt-2 mx-auto" style={{ maxWidth: 420 }}>
                  {variant.hint}
                </p>
              ) : null}

              {retryDisabled ? (
                <p className="text-sm mb-0 mt-3" style={{ color: 'var(--color-second-dark)' }} role="status">
                  Still offline — we&apos;ll enable retry as soon as you reconnect.
                </p>
              ) : null}

              <div className="d-flex flex-wrap justify-content-center align-items-center gap-3 mt-4">
                {canRetry ? (
                  <button
                    type="button"
                    className="buttons btnColor-second text-center rounded-2 px-4 py-2 fw-normal text-sm cursor-pointer"
                    onClick={handleRetry}
                    disabled={retryDisabled}
                    aria-disabled={retryDisabled}
                  >
                    {variant.retryLabel ?? 'Try again'}
                  </button>
                ) : null}

                {variant.offerSearch !== false ? (
                  <Link
                    href={searchHref}
                    className={
                      searchIsPrimary
                        ? 'buttons btnColor-second text-center rounded-2 px-4 py-2 fw-normal text-sm'
                        : 'text-sm color-text-first text-decoration-underline'
                    }
                  >
                    {variant.backLabel ?? 'Back to flight search'}
                  </Link>
                ) : (
                  // `.buttons` capitalises every word, which turned
                  // "Leisure.com" into "Leisure.Com". Wording chosen to survive
                  // that transform.
                  <Link
                    href="/"
                    className="buttons btnColor-second text-center rounded-2 px-4 py-2 fw-normal text-sm"
                  >
                    Back to home
                  </Link>
                )}
              </div>

              {/* Something to quote to support. Only for failures on our side —
                  a traveller whose price hold simply ran out has nothing to
                  report, and a reference code there would imply they do. */}
              {reference && error?.code && error.code !== 'FLIGHT_SESSION_EXPIRED' ? (
                <p className="flight-review-ref color-text-gray mb-0 mt-4">
                  If it keeps happening, quote reference{' '}
                  <span style={{ userSelect: 'all' }}>{reference}</span>
                </p>
              ) : null}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
