'use client';

import { useState } from 'react';
import type { FareOption, FareRules } from './types';
import FareFeatureList from './FareFeatureList';

interface FlightFareCardProps {
  fare: FareOption;
  /** Radio group name — one per flight, so two legs do not share a selection. */
  groupName: string;
  selected: boolean;
  disabled?: boolean;
  onSelect: (id: string) => void;
  onOpenRules: (name: string, rules: FareRules) => void;
  /**
   * corp (LEIS-962): In policy / the fare's flags, rendered under the price.
   *
   * A node rather than a verdict object, so this card stays a presentation
   * component and the whole travel-policy dependency lives in the one place
   * that already knows about it. Undefined — no business session, or the
   * limits could not be loaded — renders the card exactly as upstream does.
   */
  policyBadge?: React.ReactNode;
}

/**
 * One fare, in the "View Fares" modal.
 *
 * Extracted because this markup existed twice — once in the round-trip branch
 * and once in the single-flight one — and had already drifted: one centred its
 * contents and the other left-aligned them, one put the Recommended badge
 * before the title and the other after. Two copies of a card is two places to
 * get a fare wrong.
 *
 * The layout is one structure, not two. Desktop lays these out as columns side
 * by side; at phone widths CSS turns the same markup into a stacked row with
 * the price pulled up beside the name. A separate mobile card would be the
 * same drift again, one breakpoint along.
 */
export default function FlightFareCard({
  fare,
  groupName,
  selected,
  disabled = false,
  onSelect,
  onOpenRules,
  policyBadge,
}: FlightFareCardProps) {
  /**
   * Below the first group, everything is collapsed on a phone.
   *
   * A fare can carry a dozen inclusions across three groups. Stacked on a
   * 375px screen that is a full viewport per card, so comparing two of them
   * means scrolling past one to reach the other — which is the comparison the
   * modal exists to make. Baggage stays open because it is what people
   * actually choose on; the rest is one tap away.
   *
   * Desktop ignores this entirely: `.flight-fare-more` is only hidden by the
   * mobile media query, so a wide screen shows every group at once as before.
   */
  const [expanded, setExpanded] = useState(false);
  const groupCount = fare.featureGroups?.length ?? 0;
  const hasMore = groupCount > 1;

  return (
    <label
      htmlFor={`fare-${fare.id}`}
      className={`w-100 flight-fare-box h-100 border rounded-3 p-3 position-relative${
        selected ? ' is-selected' : ''
      }${expanded ? ' is-expanded' : ''}`}
    >
      {fare.recommended && (
        <span className="flight-fare-badge bgColor-second color-text-white-same">
          Recommended
        </span>
      )}

      {/*
        Radio, name and price are one row.

        On a phone the price sits at the end of that row rather than on a line
        of its own — the two things being compared across stacked cards are the
        name and the number, and putting them on one line means a flick of the
        thumb compares four fares instead of one and a half.
      */}
      <div className="flight-fare-box__head">
        <input
          className="form-check-input flex-shrink-0 mt-0"
          type="radio"
          name={groupName}
          id={`fare-${fare.id}`}
          value={fare.id}
          checked={selected}
          disabled={disabled}
          onChange={() => onSelect(fare.id)}
        />
        <h6 className="flight-fare-box__name color-text-dark fw-500 text-lg mb-0 text-start">
          {fare.name}
        </h6>
        <span className="flight-fare-box__price">
          <span className="color-text-dark text-xxl fw-600">
            {fare.currency}
            {fare.pricePerPerson}
          </span>
          <span className="text-body-tertiary text-sm"> / adult</span>
        </span>
      </div>

      {/*
        corp: the policy verdict, directly under the price it is about.

        Its own row rather than inside the head: a flag can run to two lines of
        explanation, and the head is the row people scan to compare fares.
      */}
      {policyBadge ? <div className="mt-2 text-start">{policyBadge}</div> : null}

      <div className="flight-fare-box__body">
        <FareFeatureList fare={fare} firstGroupOnly={hasMore && !expanded} />
      </div>

      {hasMore && (
        <button
          type="button"
          className="flight-fare-more flight-card-link-btn text-xs color-text-second h-auto position-relative border-0 bg-transparent p-0 mt-1 fw-600 cursor-pointer"
          aria-expanded={expanded}
          onClick={(e) => {
            // Inside a <label>, so a bare click would also toggle the radio
            // and select a fare the traveller was only reading about.
            e.preventDefault();
            e.stopPropagation();
            setExpanded((v) => !v);
          }}
        >
          {expanded ? 'Hide details' : 'Show more'}
        </button>
      )}

      {fare.fareRules && (
        <button
          type="button"
          disabled={disabled}
          className="flight-fare-rules flight-card-link-btn text-xs color-text-second h-auto position-relative border-0 bg-transparent p-0 mt-2 fw-500 cursor-pointer"
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            onOpenRules(fare.name, fare.fareRules!);
          }}
        >
          View Fare Rules
        </button>
      )}
    </label>
  );
}
