'use client';

import { useState, type ReactNode } from 'react';
import CompareToggle from './CompareToggle';
import { FlightResultPolicyBadge } from './FarePolicyBadge';
import { useCompareEntry } from './useCompareTray';
import { formatFlightMoney } from '@/services/flights/formatPrice';
import { BAGGAGE_NOT_PUBLISHED } from '@/services/flights/baggage';
import type { FlightData } from './types';
import FlightItinerary, { FlightItineraryModal, FLIGHT_DETAILS_VIEW } from './FlightItinerary';
import FlightNumbers from './FlightNumbers';
import AirlineLogo from './AirlineLogo';

interface MultiCityFlightCardProps {
  flight: FlightData;
  index: number;
  isSelected: boolean;
  onSelect: (flight: FlightData) => void;
  /**
   * Word above the price. Round-trip step 1 shows "from", because the figure is
   * the cheapest trip that outbound can produce rather than a price for it.
   */
  priceLead?: string;
  /** Line under the price — "30 return options", or a price difference. */
  priceNote?: ReactNode;
  /**
   * What the price block means when read aloud. The visible figures are split
   * across three elements ("from", "$978", "per adult", "+$25 vs cheapest"), and
   * a screen reader announcing them in sequence loses the relationship between
   * them — this gives the block one sentence instead.
   */
  priceAriaLabel?: string;
  /**
   * Replaces the default price rendering entirely: this becomes the large
   * bold figure instead of `flight.currency + flight.pricePerPerson`. Used on
   * the return step so the number a traveller compares card-to-card is the
   * extra cost over the cheapest return ("+$0", "+$142.10"), not the full
   * trip total repeated on every card. Leave unset for the default
   * lead/price/"per adult"/note layout.
   */
  priceMain?: ReactNode;
  /** Paired with `priceMain` — shown below it, smaller, in a subtle pill
   *  (e.g. "$765.83 Total round-trip price · per adult"). Ignored unless
   *  `priceMain` is also set. */
  priceSecondary?: ReactNode;
  /**
   * Offer "+ Compare" on this card.
   *
   * Opt-in because this card serves both the round-trip steps and the
   * multi-city list, and a comparison only means something where every row is
   * an alternative to every other. Multi-city rows are legs of one itinerary.
   */
  showCompare?: boolean;
  /** Overrides the unselected button text. */
  selectLabel?: string;
}

export default function MultiCityFlightCard({
  flight,
  index,
  isSelected,
  onSelect,
  priceLead,
  priceNote,
  priceAriaLabel,
  priceMain,
  priceSecondary,
  showCompare = false,
  selectLabel,
}: MultiCityFlightCardProps) {
  const [showDetails, setShowDetails] = useState(false);

  const leg = flight.outbound;
  const stopsLabel =
    leg.stops === 0 ? 'Non-stop' : leg.stops === 1 ? '1 Stop' : `${leg.stops} Stops`;
  const stopClass = leg.stops === 0 ? 'non-stop' : leg.stops === 1 ? 'one-stop' : 'multi-stop';
  const detailSectionId = `flightDetailSection${index}`;
  const toggleDetails = () =>
    FLIGHT_DETAILS_VIEW === 'modal' ? setShowDetails(true) : setShowDetails((v) => !v);

  const compare = useCompareEntry(flight);
  /** Names the flight, so "Compare" is not identical on every row. */
  const compareLabel = `${flight.outbound.airline.name} ${flight.outbound.departure.time} to ${flight.outbound.arrival.time}`;

  return (
    <div className={`card flight-card rounded-start-3 w-100 bgColor-white p-3 m-0${isSelected ? ' active' : ''}`}>
      <div className="row listing-row g-0 h-100">

        {/* Left block: col-md-10 */}
        <div className="col-md-10">
          <div className="row">

            {/* col-xxl-2: airline logo + name + mobile price */}
            <div className="col-xxl-2 text-center col-xl-2 ps-0 col-lg-2 col-md-2 col-sm-12 col-12 h-100 pt-2 pe-md-0 d-flex flex-wrap d-md-block order-1 order-md-1">
              <div className="flight-view ps-2">
                { }
                <AirlineLogo code={leg.airline.code} name={leg.airline.name} className="flight-airline-logo" />
                <div className="flight-details text-start text-md-center xs-2">
                  <div className="subHeading text-capitalize text-sm color-text-dark fw-bolder mb-0 mt-2">
                    {leg.airline.name}
                  </div>
                  <FlightNumbers numbers={leg.airline.flightNumbers ?? [leg.airline.flightNumber]} />
                </div>
              </div>
              <div className="flight-starting-price d-block d-sm-none ms-auto text-end pt-4 mt-2 md-pt-0 md-mt-0">
                <div className="listing-div text-end d-flex flex-column align-items-end">
                  {priceMain ? (
                    <>
                      <h5 className="mb-0">
                        <span className="mainHeading flight-price-amount color-text-dark fw-bold">
                          {priceMain}
                        </span>
                      </h5>
                      <small className="d-block flight-detail-label text-xs mt-1 mb-2">per adult</small>
                      {priceSecondary && (
                        <small className="d-inline-block text-xs flight-price-secondary">{priceSecondary}</small>
                      )}
                    </>
                  ) : (
                    <>
                      <small className="d-block mb-2 text-xs">{priceLead ?? 'from'}</small>
                      <h5 className="mb-0">
                        <span className="mainHeading flight-price-amount color-text-dark fw-bold">
                          {formatFlightMoney(flight.currency, flight.pricePerPerson)}
                        </span>
                      </h5>
                      <small className="d-block color-text-dark text-xs mb-md-2">per adult</small>
                      {priceNote && <small className="d-block text-xs flight-detail-label">{priceNote}</small>}
                    </>
                  )}
                  {/* corp (LEIS-981): the same verdict the round-trip and
                      one-way cards carry. Nothing renders outside Business. */}
                  <FlightResultPolicyBadge flight={flight} />
                </div>
              </div>
            </div>

            {/* col-xxl-10: flight routes + features */}
            <div className="col-xxl-10 col-xl-10 col-lg-10 col-md-10 col-sm-12 col-12 h-100 booking-content-details p-0 pe-md-5 order-2 order-md-2">
              <div className="flight-routes d-flex flex-wrap flex-md-nowrap align-items-center border-bottom pb-3">
                <div className="flex-grow-1 px-3 w-s-100 order-md-2">
                  <div className="flight-path position-relative w-100">
                    <div className="path-line" />
                    <span className="path-dot dot-start bg-white" />
                    <span className="path-dot dot-end" />
                    {leg.stops > 0 && <span className="path-dot dot1" />}
                    <span className="plane bgColor-white px-1 me-2">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width={18}
                        height={18}
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="#f45d6b"
                        strokeWidth={2}
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        className="lucide lucide-plane absolute top-1/2 right-0 -translate-y-1/2 translate-x-1/2 w-4 h-4"
                      >
                        <path d="M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z" />
                      </svg>
                    </span>
                  </div>
                  <div className="time text-center">
                    <span className="text-xs text-grey me-2">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width={11}
                        height={11}
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="#bdbdbd"
                        strokeWidth={2}
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        className="lucide lucide-clock w-3 h-3 text-gray-400"
                      >
                        <circle cx={12} cy={12} r={10} />
                        <polyline points="12 6 12 12 16 14" />
                      </svg>
                      {leg.duration}
                    </span>
                    <span className={`text-xs px-2 py-1 rounded-5 ${stopClass}`}>
                      {stopsLabel}
                    </span>
                    {leg.stops > 0 && leg.stopInfo && (
                      <div className="route-diversion text-xs text-grey mt-2 w-100">
                        {leg.stopInfo}
                      </div>
                    )}
                  </div>
                </div>
                <div className="w-s-50 order-md-1 pe-sm-1 ps-2">
                  <div className="color-text-dark font-inter fw-bolder text-xl">{leg.departure.time}</div>
                  <div className="color-text-black fw-normal font-inter text-sm">{leg.departure.airport}</div>
                  <div className="flight-detail-label text-sm">{leg.departure.city}</div>
                </div>
                <div className="w-s-50 text-end order-md-3">
                  <div className="color-text-dark font-inter fw-bolder text-xl">
                    {leg.arrival.time}
                    {leg.arrival.nextDay && <sup className="color-text-second text-xs">+1</sup>}
                  </div>
                  <div className="color-text-black text-sm">{leg.arrival.airport}</div>
                  <div className="flight-detail-label text-sm">{leg.arrival.city}</div>
                </div>
              </div>

              <div className="d-md-flex justify-content-between align-items-center gap-2">
                <div className="flight-features pt-3 d-flex flex-wrap align-items-center gap-md-3 gap-2 ps-2">
                  {leg.cabin && (
                    <div className="cabin text-sm text-grey">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width={15}
                        height={15}
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="#bdbdbd"
                        strokeWidth={2}
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        className="lucide lucide-luggage w-3.5 h-3.5 text-gray-400"
                      >
                        <path d="M6 20a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2" />
                        <path d="M8 18V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v14" />
                        <path d="M10 20h4" />
                        <circle cx={16} cy={20} r={2} />
                        <circle cx={8} cy={20} r={2} />
                      </svg> {" "}
                      Cabin: {leg.cabin}
                    </div>
                  )}
                  {leg.checkin && (
                    <div className="checkin text-sm text-grey">
                      <svg
                        xmlns="http://www.w3.org/2000/svg"
                        width={15}
                        height={15}
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="#bdbdbd"
                        strokeWidth={2}
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        className="lucide lucide-luggage w-3.5 h-3.5 text-gray-400"
                      >
                        <path d="M6 20a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2" />
                        <path d="M8 18V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v14" />
                        <path d="M10 20h4" />
                        <circle cx={16} cy={20} r={2} />
                        <circle cx={8} cy={20} r={2} />
                      </svg> {" "}
                      Check-in: {leg.checkin}
                    </div>
                  )}
                  {/* Per leg here, not per card: a multi-city trip can carry a
                      different allowance on each leg, so a single card-level
                      note would be claiming more than we know. */}
                  {!leg.cabin && !leg.checkin && (
                    <div className="baggage-unpublished text-sm text-grey">
                      {BAGGAGE_NOT_PUBLISHED}
                    </div>
                  )}
                </div>
                {leg.refundStatus && (
                  <div className="refund text-xs text-nowrap rounded-5 d-inline-block px-2 py-1 mt-3 ms-2 ms-sm-0">
                    {leg.refundStatus}
                  </div>
                )}
              </div>
            </div>

          </div>
        </div>

        {/* Right block: col-md-2 */}
        <div className="col-md-2">
          <div className="col-12 border-start no-mobile-border ps-2 pe-md-2 no-grid order-2 order-md-3 h-100">
            <div className="d-flex flex-column justify-content-center align-items-end text-end h-100">
              <div
                className="listing-div text-end d-flex justify-content-between align-items-end flex-column d-none d-sm-block"
                {...(priceAriaLabel ? { role: 'text', 'aria-label': priceAriaLabel } : {})}
              >
                {priceMain ? (
                  <>
                    <h5 className="mb-0">
                      <span className="mainHeading flight-price-amount color-text-dark fw-bold">
                        {priceMain}
                      </span>
                    </h5>
                    <small className="d-block flight-detail-label text-xs mt-1 mb-2">per adult</small>
                    {priceSecondary && (
                      <small className="d-inline-block text-xs flight-price-secondary">{priceSecondary}</small>
                    )}
                  </>
                ) : (
                  <>
                    {priceLead && <small className="d-block text-xs flight-detail-label">{priceLead}</small>}
                    <h5 className="mb-0">
                      <span className="mainHeading flight-price-amount color-text-dark fw-bold">
                        {formatFlightMoney(flight.currency, flight.pricePerPerson)}
                      </span>
                    </h5>
                    <small className="d-block color-text-dark text-xs mb-md-2">
                      per adult
                    </small>
                    {priceNote && <small className="d-block text-xs flight-detail-label">{priceNote}</small>}
                  </>
                )}
                {/* corp (LEIS-981), as above. */}
                <FlightResultPolicyBadge flight={flight} />
              </div>
              <div className="d-flex d-md-block w-100 justify-content-between">
                <a
                  role="button"
                  className={`toggle-text-btn buttons text-center rounded-2 px-3 py-1 fw-normal position-relative me-0 w-auto text-sm mt-1 order-2 order-md-3 cursor-pointer${isSelected ? ' btnColor-first-outline' : ' btnColor-second'}`}
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    onSelect(flight);
                  }}
                >
                  <span className={`toggle-btn-text text-sm fw-400${isSelected ? ' color-text-second' : ' color-text-white-same'}`}>
                    {isSelected ? 'Selected ✓' : (selectLabel ?? 'Select')}
                  </span>
                </a>
                <a
                  className="order-1 order-md-4"
                  href={`#${detailSectionId}`}
                  onClick={(e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    toggleDetails();
                  }}
                >
                  <small
                    className="listing-div d-block fw-regular color-text-second mb-0 text-xs mt-md-2 mb-md-2 mt-3 flightnew-detail toggle-text-btn flight-card-link-btn cursor-pointer"
                    aria-expanded={FLIGHT_DETAILS_VIEW === 'inline' ? showDetails : undefined}
                    aria-controls={FLIGHT_DETAILS_VIEW === 'inline' ? detailSectionId : undefined}
                  >
                    <span className="toggle-btn-text color-text-second text-xs fw-400">
                      {FLIGHT_DETAILS_VIEW === 'inline' && showDetails ? 'Hide Details' : 'Flight Details'}
                    </span>
                    <svg
                      className="iconSize-12 stroke-second flight-card-chevron"
                      width={24}
                      height={24}
                      viewBox="0 0 24 24"
                      fill="none"
                      strokeWidth={2}
                    >
                      <path d="m6 9 6 6 6-6" />
                    </svg>
                  </small>
                </a>
              </div>
            </div>
          </div>
        </div>

      </div>

      {showCompare && compare.available && (
        <div className="flight-card-compare-row" onClick={(e) => e.stopPropagation()}>
          <CompareToggle
            id={`compare-rt-${index}`}
            isAdded={compare.isAdded}
            isFull={compare.isFull}
            onAdd={compare.add}
            onRemove={compare.remove}
            flightLabel={compareLabel}
          />
        </div>
      )}

      {/* Expandable panels */}
      <div className="flight-card-extra-info" id={`flightCardExtraInfo${index}`} onClick={(e) => e.stopPropagation()}>

        {/* Itinerary detail section */}
        {FLIGHT_DETAILS_VIEW === 'inline' && (
          <div className={`collapse${showDetails ? ' show' : ''}`} id={detailSectionId}>
            <FlightItinerary flight={flight} />
          </div>
        )}

      </div>

      {FLIGHT_DETAILS_VIEW === 'modal' && (
        <FlightItineraryModal flight={flight} isOpen={showDetails} onClose={() => setShowDetails(false)} />
      )}
    </div>
  );
}
