"use client";

import Image from "next/image";
import { Check } from "lucide-react";
import type { ReactNode } from "react";
import type {
  FlightAddOnTraveler,
  FlightBagCatalogueOption,
  FlightBagOptionGroup,
  FlightReviewViewModel,
} from "@/services/flights/types";
import {
  BAGGAGE_NOT_PUBLISHED,
  describeBaggageAllowance,
} from "@/services/flights/baggage";
import {
  POPULAR_EXTRA_BAG_QUANTITY,
  bagSelectionKey,
  extraBagCardTitle,
  extraBagOptionLabel,
} from "@/services/flights/bags";
import { formatFlightMoney } from "@/services/flights/formatPrice";

/**
 * Bag illustrations, keyed by how many bags a card is offering.
 *
 * Two files cover every case. Amadeus can price three or more bags in one
 * option, and the two-bag artwork stands in for "several" there — the title
 * carries the exact count ("3× extra checked bags"), so the picture only has to
 * say "more than one". A stand-in beats a broken image on a card whose whole
 * purpose is to show you the thing you are buying.
 */
const BAG_ART_ONE = "/images/flights/baggage/checked-bag-1x.png";
const BAG_ART_MANY = "/images/flights/baggage/checked-bag-2x.png";

function bagArtFor(quantity: number): string {
  return quantity <= 1 ? BAG_ART_ONE : BAG_ART_MANY;
}

/**
 * The weight line under a card's description, or nothing.
 *
 * Weight only — never a size. Amadeus files no dimensions on a bag option, on
 * any carrier in any response we have, so the "up to 158 cm L+W+H" half of the
 * design has no source and is omitted rather than filled with a plausible
 * number. It files weight on some carriers and not others, so this is absent
 * more often than not; `describeBaggageAllowance` returns undefined in that
 * case and the line does not render at all.
 *
 * Quantity is deliberately not passed in: the card's own title already says how
 * many bags this is, and the shared formatter would otherwise repeat it here as
 * "1 piece (23 KG)".
 */
function weightLine(bag: { weight?: number; weightUnit?: string }): string | undefined {
  if (typeof bag.weight !== "number") return undefined;
  const described = describeBaggageAllowance({
    weight: bag.weight,
    weightUnit: bag.weightUnit,
  });
  return described ? `(${described})` : undefined;
}

/**
 * How the Included card describes an allowance the fare already carries.
 *
 * Four real cases, because Amadeus files all four (see baggage.ts's own count
 * over 1,100 allowance slots):
 *
 *   {quantity: 2}              "2× checked bags"        — the common one
 *   {quantity: 0}              "No checked bags included" — a published zero
 *   {weight: 15, unit: 'KG'}   "Checked baggage included" + a 15 KG line
 *   absent                     "No extra bags"          — nothing was published
 *
 * The last is not the same as the third-from-last and must not borrow its
 * wording: an airline that published nothing has not told us the fare includes
 * nothing. The card still has to render — it is also the "no extra bags" choice
 * — so it says only what it can stand behind and points at the airline.
 */
function includedCardCopy(bag: FlightAddOnTraveler["includedCheckedBags"]): {
  title: string;
  description: string;
} {
  if (bag?.quantity === 0) {
    return {
      title: "No checked bags included",
      description: "This fare does not include checked baggage",
    };
  }
  if (typeof bag?.quantity === "number" && bag.quantity > 0) {
    return {
      title: `${bag.quantity}× checked bag${bag.quantity === 1 ? "" : "s"}`,
      description: "Included in your fare",
    };
  }
  if (typeof bag?.weight === "number") {
    return { title: "Checked baggage included", description: "Included in your fare" };
  }
  return { title: "No extra bags", description: BAGGAGE_NOT_PUBLISHED };
}

/**
 * One selectable baggage card.
 *
 * ## Why a native radio and not `role="radio"`
 *
 * The hit area is a `<label>` stretched across the whole card with a
 * visually-hidden `<input type="radio">` inside it. That hands arrow-key
 * navigation, Enter/Space, roving focus, the "selected" announcement and the
 * group semantics to the browser, instead of to a keydown handler that has to
 * be kept correct forever. `.visually-hidden` clips the input rather than
 * hiding it, so it stays focusable and stays in the accessibility tree.
 *
 * ## Why `action` sits outside the label
 *
 * A selected card offers a real "Remove" button, and a `<button>` nested inside
 * a `<label>` re-triggers that label on the way up — the card would deselect
 * and immediately reselect. As a *sibling* of the label it does not, because
 * label activation only follows clicks that land inside the label. So the card
 * is the grid, the label is an absolutely-positioned overlay providing the hit
 * area, and `action` is a normal grid child stacked above it.
 *
 * ## Selection is not shown by colour alone
 *
 * Three things change together: the border weight and colour, the background
 * tint, and the action's own label ("Add for $192" → "✓ Added · Remove").
 */
function BagCard({
  radio,
  art,
  title,
  badge,
  description,
  allowance,
  action,
}: {
  /**
   * Makes the card a choice. Omitted, it is a statement instead — which is what
   * the Included card becomes on a fare whose legs price their bags separately
   * (see TravelerBags).
   */
  radio?: {
    inputId: string;
    name: string;
    value: string;
    checked: boolean;
    onSelect: () => void;
    /**
     * What a screen reader announces for this choice, e.g. "1 extra checked
     * bag, $192.00". Set explicitly because the card's accessible name would
     * otherwise be every word printed on it, price and description included.
     */
    ariaLabel: string;
  };
  art: string;
  title: string;
  badge?: ReactNode;
  description: string;
  allowance?: string;
  action: ReactNode;
}) {
  const selected = radio?.checked === true;
  return (
    <div
      className={`fb-bagcard${radio ? "" : " is-static"}${selected ? " is-selected" : ""}`}
    >
      {radio ? (
        <label className="fb-bagcard__hit">
          <input
            className="visually-hidden"
            type="radio"
            id={radio.inputId}
            name={radio.name}
            value={radio.value}
            checked={radio.checked}
            onChange={radio.onSelect}
            aria-label={radio.ariaLabel}
          />
        </label>
      ) : null}

      {/*
        alt="" on purpose. The illustration repeats what the title beside it
        already says, so naming it would have a screen reader announce the bag
        twice. An explicit empty alt is what marks an image decorative — it is
        not a missing alt attribute. Width and height are set so the row
        reserves its space before the PNG arrives.
      */}
      <Image className="fb-bagcard__art" src={art} alt="" width={96} height={96} />

      <div className="fb-bagcard__body">
        <p className="fb-bagcard__title mb-0">
          {title}
          {badge}
        </p>
        <p className="fb-bagcard__desc mb-0">{description}</p>
        {allowance ? <p className="fb-bagcard__allowance mb-0">{allowance}</p> : null}
      </div>

      <div className="fb-bagcard__action">{action}</div>
    </div>
  );
}

/** "✓ Added · Remove" — the selected extra-bag card's own way back to none. */
function RemoveButton({ label, onRemove }: { label: string; onRemove: () => void }) {
  return (
    <button type="button" className="fb-bagcard__remove" onClick={onRemove}>
      <Check size={14} aria-hidden="true" />
      {/*
        Hidden from the accessible name, not from the screen: the radio itself
        already announces "selected", so repeating it here would make the
        button's name "Added Remove 1 extra checked bag". What is left — "Remove
        1 extra checked bag" — still contains the visible word the user would
        speak, which is what WCAG's label-in-name rule asks for.
      */}
      <span aria-hidden="true">Added&nbsp;·&nbsp;</span>
      <span>Remove</span>
      <span className="visually-hidden"> {label}</span>
    </button>
  );
}

/**
 * The extra-bag cards for one segment group, as one radio group.
 *
 * `includedCard` is threaded in rather than rendered by the caller because on a
 * single-group fare the Included card IS this group's "no extra bags" option —
 * see TravelerBags for why that stops being true once a fare prices its legs
 * separately.
 */
function BagGroup({
  traveler,
  group,
  currencySymbol,
  selected,
  onSelect,
  includedCard,
}: {
  traveler: FlightAddOnTraveler;
  group: FlightBagOptionGroup;
  currencySymbol: string;
  selected: string;
  onSelect: (optionId: string) => void;
  includedCard?: (args: {
    name: string;
    checked: boolean;
    onSelectNone: () => void;
  }) => ReactNode;
}) {
  const name = `bags-${traveler.travelerId}-${group.groupId}`;
  const priceOf = (opt: FlightBagCatalogueOption) => {
    const amount = Number.parseFloat(opt.amount);
    return Number.isFinite(amount)
      ? formatFlightMoney(currencySymbol, amount)
      : `${currencySymbol}${opt.amount}`;
  };

  return (
    <fieldset className="fb-baggroup">
      <legend className="fb-baggroup__legend">
        Add extra bags
        {group.label ? <span className="fb-baggroup__scope"> · {group.label}</span> : null}
      </legend>

      {includedCard?.({ name, checked: selected === "", onSelectNone: () => onSelect("") })}

      <div className="fb-baggroup__cards">
        {/*
          Without an Included card standing in for it, the group still needs a
          reachable "none" — otherwise a traveller who picks a bag on a
          multi-group fare has no way to unpick it with the keyboard, and the
          radio group has no unselected member to arrow back to.
        */}
        {!includedCard ? (
          <BagCard
            radio={{
              inputId: `${name}-none`,
              name,
              value: "",
              checked: selected === "",
              onSelect: () => onSelect(""),
              ariaLabel: "No extra bags",
            }}
            art={BAG_ART_ONE}
            title="No extra bags"
            description="Keep the allowance included in your fare"
            action={<span className="fb-bagcard__included">Included</span>}
          />
        ) : null}

        {group.options.map((opt) => {
          const isSelected = selected === opt.id;
          const price = priceOf(opt);
          const spokenLabel = extraBagOptionLabel(opt);
          return (
            <BagCard
              key={opt.id}
              radio={{
                inputId: `${name}-${opt.id}`,
                name,
                value: opt.id,
                checked: isSelected,
                onSelect: () => onSelect(opt.id),
                ariaLabel: `${spokenLabel}, ${price}`,
              }}
              art={bagArtFor(opt.quantity)}
              title={extraBagCardTitle(opt)}
              badge={
                POPULAR_EXTRA_BAG_QUANTITY === opt.quantity ? (
                  <span className="fb-bagcard__pill">Popular</span>
                ) : null
              }
              description="Dropped off at check-in"
              allowance={weightLine(opt)}
              action={
                isSelected ? (
                  <RemoveButton label={spokenLabel} onRemove={() => onSelect("")} />
                ) : (
                  <span className="fb-bagcard__price">Add for {price}</span>
                )
              }
            />
          );
        })}
      </div>
    </fieldset>
  );
}

function TravelerBags({
  traveler,
  currencySymbol,
  selections,
  onSelectionChange,
}: {
  traveler: FlightAddOnTraveler;
  currencySymbol: string;
  selections: Record<string, string>;
  onSelectionChange: (key: string, optionId: string) => void;
}) {
  const included = includedCardCopy(traveler.includedCheckedBags);
  const includedAllowance = weightLine(traveler.includedCheckedBags ?? {});

  /*
   * Who owns the "no extra bags" radio.
   *
   * The design folds the Included card and the old "No extra bags · Included"
   * row into one: the card shows the allowance you already have AND is the
   * choice you are on when you have added nothing. That works because there is
   * one radio group to be the unselected member of.
   *
   * A fare that prices its legs separately has one radio group per leg, and a
   * single card cannot be the unselected member of two of them at once. There
   * the Included card steps back to being what it says it is — a statement of
   * the fare's allowance — and each leg carries its own "No extra bags" card.
   * One group is overwhelmingly the common case and renders exactly as drawn.
   */
  const includedIsTheNoneChoice = traveler.groups.length === 1;

  const renderIncludedCard = (args?: {
    name: string;
    checked: boolean;
    onSelectNone: () => void;
  }) => (
    <BagCard
      radio={
        args
          ? {
              inputId: `${args.name}-none`,
              name: args.name,
              value: "",
              checked: args.checked,
              // The group's own clear, handed down rather than reconstructed
              // from `groups[0]` — correct even if the single-group precondition
              // below ever stops holding.
              onSelect: args.onSelectNone,
              ariaLabel: `${included.title}, no extra bags`,
            }
          : undefined
      }
      art={bagArtFor(traveler.includedCheckedBags?.quantity ?? 1)}
      title={included.title}
      description={included.description}
      allowance={includedAllowance}
      action={
        <span className="fb-bagcard__included">
          <Check size={14} aria-hidden="true" />
          Included
        </span>
      }
    />
  );

  return (
    <div className="bgColor-white shadow-sm rounded-3 review-flight-card">
      <div className="review-flight-card-header p-3 rounded-3 rounded-bottom-0">
        <h3 className="subHeading mb-0 text-uppercase fw-bold">{traveler.label}</h3>
      </div>
      <div className="p-3 d-flex flex-column gap-3">
        {includedIsTheNoneChoice ? null : renderIncludedCard()}

        {traveler.groups.map((group) => {
          const key = bagSelectionKey(traveler.travelerId, group.groupId);
          return (
            <BagGroup
              key={group.groupId}
              traveler={traveler}
              group={group}
              currencySymbol={currencySymbol}
              selected={selections[key] ?? ""}
              onSelect={(optionId) => onSelectionChange(key, optionId)}
              includedCard={
                includedIsTheNoneChoice
                  ? (args) => renderIncludedCard(args)
                  : undefined
              }
            />
          );
        })}
      </div>
    </div>
  );
}

export default function PaneAddOns({
  review,
  selections = {},
  onSelectionChange,
}: {
  review?: FlightReviewViewModel;
  selections?: Record<string, string>;
  onSelectionChange?: (key: string, optionId: string) => void;
}) {
  const travelers = review?.addOns?.travelers ?? [];
  const currencySymbol = review?.addOns.currencySymbol || review?.currencySymbol || "$";

  return (
    <div
      className="fb-pane"
      data-step-title="Add-ons Summary"
      data-next-label="Continue to Payment"
      data-total-label="Grand Total"
      data-footer-note="You can skip add-ons and continue"
    >
      <div className="d-flex flex-column gap-3">
        <div>
          <h4 className="text-lg fw-600 mb-0">Enhance Your Journey</h4>
          <p className="text-sm">
            {travelers.length
              ? "Extra checked bags are optional — skip if you prefer"
              : "No extra bags are available on this fare — you can continue"}
          </p>
        </div>

        {travelers.length === 0 ? (
          <div className="bgColor-white shadow-sm rounded-3 p-3">
            <p className="text-sm mb-0">
              This fare does not offer extra checked bags before payment. You can add
              checked bags later with the airline or at the airport.
            </p>
          </div>
        ) : (
          travelers.map((traveler) => (
            <TravelerBags
              key={traveler.travelerId}
              traveler={traveler}
              currencySymbol={currencySymbol}
              selections={selections}
              onSelectionChange={onSelectionChange ?? (() => {})}
            />
          ))
        )}
      </div>
    </div>
  );
}
